我正在努力找出这段代码的错误.这目前在Objective-C中有效,但在Swift中,这只是在方法的第一行崩溃.它在控制台日志(log)中显示一条错误消息:Bad_Instruction.

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!  {
        var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell

        if (cell == nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
        }

        cell.textLabel.text = "TEXT"
        cell.detailTextLabel.text = "DETAIL TEXT"

        return cell
    }

推荐答案

Also see 100 which contains the second half of the solution

让我们在不创建自定义子类或NIB的情况下找到解决方案

真正的问题在于,Swift 区分了可以为空的对象(nil)和不能为空的对象.如果您没有为标识符注册nib,那么dequeueReusableCellWithIdentifier可以返回nil.

这意味着我们必须将变量声明为可选:

var cell : UITableViewCell?

我们必须用as?而不是as来施法

//variable type is inferred
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell

if cell == nil {
    cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}

// we know that cell is not empty now so we use ! to force unwrapping but you could also define cell as
// let cell = (tableView.dequeue... as? UITableViewCell) ?? UITableViewCell(style: ...)

cell!.textLabel.text = "Baking Soda"
cell!.detailTextLabel.text = "1/2 cup"

cell!.textLabel.text = "Hello World"

return cell

Swift相关问答推荐

将参数集从一个对象复制到另一个对象的最佳方法

Accelerate的SparseMultiply随机崩溃,EXC_BAD_ANCE

启用完成并发判断以及如何解决警告(续)

绑定到可选值的非可选属性?'

UICollectionViewCompostionalLayout Collectionview单元格宽度在重新加载数据后未正确调整大小

在不传递参数的情况下使用Init方法?

可选,类似于自定义类型的初始化

解码器是否需要具有密钥的外部数据表示?

将matchedGeometryEffect 应用于列表视图内的视图时,列表视图中的项目会受到影响 - SwiftUI

使用变量(而非固定)的字符串分量进行Swift正则表达式

UIBezierPath() 和 DragGesture:连接点创建角而不是曲线

SwiftUI 从任务中安全更新状态变量

使用 Async-Await 和 Vapor-Fluent 创建 CRUD 函数 - Swift 5.6

在 macOS (Swift) 上获取 BSD 驱动器名称的最佳方法是什么?

Swift - 给定一个像 30 的 Int 如何将范围数乘以 7?

Xcode:方法参数的代码完成

如何使用 Swift/iOS 为人类书写的笔画制作动画?

UITableViewCell 不显示 detailTextLabel.text - Swift

如何使用 Swift 将文本文件逐行加载到数组中?

如何在 SwiftUI 中的一个视图上显示两个alert ?