gpt4 book ai didi

ios - 裁缝强制转换冲突

转载 作者:行者123 更新时间:2023-11-28 06:43:31 25 4
gpt4 key购买 nike

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell

这是实现 TableView 单元格属性的标准语句。但是 Tailor(它是一个 Swift 分析器/linter)警告说你不应该强制 CustomTableViewCell as as! 如果我以前是 as?,我必须实现单元格的属性作为 cell!。但是 Tailor 没有警告 [forced-type-cast] Force casts should be avoided。这是什么原因?如何在不将单元格解包为单元格的情况下实现单元格! Swift 中强制转换操作的正确编程范例是什么?

最佳答案

我不熟悉“Tailor”,但很可能它给你这个警告的原因是因为如果强制转换失败,那么很明显你的程序会崩溃,那永远不会好。

as! 运算符确实有其用武之地,如果您 100% 确定所转换的是该类型的话。但是,即便如此,安全总比后悔好,您应该改用 guardif let 语句来处理失败的转换。

if let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? CustomTableViewCell {
//do what you like with cell
}

guard let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? CustomTableViewCell else {
//abort current scope, return, break, etc. from scope.
}
//do what you like with cast cell

关于ios - 裁缝强制转换冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com