ios - 在 Swift 中编写自定义 UITableViewCell 时强制向下转换

标签 ios swift cocoa-touch

在下面的代码中:

let cell = tableView.dequeueReusableCell(
    withIdentifier: "MyCell",
    for: indexPath
) as MyTableViewCell  // 'UITableViewCell' is not convertible to 'MyTableViewCell'; did you mean to use 'as!' to force downcast?

我们有错误提示 UITableViewCell 不能转换为 MyTableViewCell

因此编译器建议进行强制转换:

let cell = tableView.dequeueReusableCell(
    withIdentifier: "MyCell",
    for: indexPath
) as! MyTableViewCell  // ?!?!?!

但是,这感觉很难看。

在处理 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 时,是否没有强制转换的替代方法?这真的是在 Swift 中实现这一目标的最惯用的方法吗?

谢谢!

最佳答案

Is this really the most idiomatic way

当然。这是完全标准的。

可以像这样安全地垂头丧气:

if let cell = tableView.dequeueReusableCell(
   withIdentifier: "MyCell",
   for: indexPath
) as? MyTableViewCell {

但在这种情况下,我认为不值得这样做,因为如果结果证明这不是 MyTableViewCell,那么您确实希望崩溃。 p>

关于ios - 在 Swift 中编写自定义 UITableViewCell 时强制向下转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42169147/

相关文章:

ios - iOS6 中的社交分享面板

ios - iOS 中的音频信号处理

iphone - 安装 Facebook SDK - iPhone

iOS - 异步请求和 UI 交互

ios - 自动签名无法解决 "Project"目标权利的问题

iphone - 在 dealloc 中的 iVar 上使用 self 吗?

iOS - 在其他 View 之上设置模糊图像,奇怪的问题

ios - Swift 3.0,Alamofire 4.0 调用中的额外参数 'method'

objective-c - 在 prepareForSegue 中传递对 ViewController 的引用

ios - UITableView 不加载数据