我尝试在实现cellForRowAtIndexPath
协议的ViewController
中实现函数UITableViewDataSource
:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell;
if !cell {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
cell.textLabel.text = "row \(indexPath.row)";
cell.detailTextLabel.text = "row details \(indexPath.row)"
return cell;
}
它是来自Objective-c代码对应物的忠实翻译(我想)。
但是,swift编译器会标记此错误消息:"' UITableViewCell'不是' NSNumber'"
的子类型
如果我将实现更改为
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell;
cell.textLabel.text = "row \(indexPath.row)";
// cell.detailTextLabel.text = "row details \(indexPath.row)"
return cell;
}
编译器错误消失了,应用程序似乎按照我的预期工作。
我的问题:
1)为什么swift编译器发出此错误消息?
2)测试变量cell
的正确语法是否为null?在这里,NSNumber显然很快。是因为!
运算符吗?
3)检查cell
是否为空是否有意义?我想当我在as UITableViewCell
电话中使用dequeueReusableCellWithIdentifier
时,我已经排除了零的可能性。 swift因此保证函数dequeueReusableCellWithIdentifier
总是返回UITableViewCell吗?它与objective-c行为不同。
答案 0 :(得分:4)
你必须明确地测试nil。请参阅XCode 6 Beta 5的发行说明。
if cell != nil {
...
}
但编译器消息具有误导性。
Optionals不再符合BooleanType(以前的LogicValue)协议,因此它们也是如此 可能不再用于代替布尔表达式(必须明确地与它们进行比较) v!= nil)。