在Swift 2.0中定义“UITableViewCell”变量

3
我正在尝试使用Swift创建UITableViewCell类型变量,以下是我的代码:
 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dwarves.count
    }
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier)! as UITableViewCell if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier) }
cell.textLabel?.text = dwarves[indexPath.row] return cell }
在第七行的if (cell == nil),它给了我一个错误,即UITableViewCell类型的值永远不可能为nil,因此不允许比较。它不能被替换为if (!cell)。我该如何修复这些代码?
3个回答

4

如果你确实想使用过时的方法tableView.dequeueReusableCellWithIdentifier(_:),你可以这样做:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) ?? UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
    cell.textLabel?.text = dwarves[indexPath.row]

    return cell
}

但是最好使用dequeueReusableCellWithIdentifier(_:forIndexPath:),它永远不会返回nil
使用它需要与registerClass(_:forCellReuseIdentifier:)registerNib(_:forCellReuseIdentifier:)一起使用。


1
根据苹果文档dequeReusableCellWithIdentifier返回一个可选值:
 func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell?

但是在你的代码中,你明确地展开了这个值,因为你的cell对象是一个UITableViewCell对象。

你应该使用- dequeueReusableCellWithIdentifier:forIndexPath::它的返回值不是可选的,因此你不必展开你的cell。


0

由于非可选类型不能与nil进行比较(只有可选变量包含nil值)。例如,如果您想要检查 nil,只需使用这种方式即可。我在Playground中实现了它。

let tableView = UITableView()
let index = NSIndexPath()
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("")
//then make check for nil if you want
if (cell == nil) {
    print("its nil")
} else  {
    print("not nil")
}

是的,我已经审查了“cell”,并且它收到了nil。但是如何审查所有可能的值,如果它们中有一个是nil呢? - pakgwan luk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接