如a中所示之前对类似问题的回答, -tableView:cellForRowAtIndexPath:
必须返回一个UITableViewCell
。所以你无法返回nil
。但是,我还建议避免在末尾返回以下代码-tableView:cellForRowAtIndexPath:
当你使用if else or switch里面的语句:
//bad code design
var cell: UITableViewCell!
return cell
or:
//bad code design
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
return cell
您可以编写比创建更好的代码UITableViewCell
永远不会调用的实例只是为了消除 Xcode 警告!
那么解决方案是什么呢?
关键是要确保您的最后可能值if else语句设置在else
(不在else if
)。同样,关键是要确保您的最后可能值switch语句设置在default:
(不在case XXX:
).
因此,您的代码应如下所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("CellZero", forIndexPath: indexPath) as UITableViewCell
/* ... */
return cell
} else if indexPath.row == 1 {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("CellOne", forIndexPath: indexPath) as CellOne
/* ... */
return cell
} else { //set your last indexPath.row case in "else", not in "else if indexPath.row == 2"!!!
switch segment {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("CellTwo", forIndexPath: indexPath) as CellTwo
/* ... */
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("CellThree", forIndexPath: indexPath) as CellThree
/* ... */
return cell
default: //set your last segment case in "default:", not in "case 2:"!!!
let cell = tableView.dequeueReusableCellWithIdentifier("CellFour", forIndexPath: indexPath) as CellFour
/* ... */
return cell
}
}
//No need for a fictive "return cell" with this code!!!
}
If segment
不是一个可选的,感谢tuples,您甚至可以将前面的代码简化为:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch (indexPath.row, segment) {
case (0, _):
let cell = tableView.dequeueReusableCellWithIdentifier("CellZero", forIndexPath: indexPath) as UITableViewCell
/* ... */
return cell
case (1, _):
let cell = tableView.dequeueReusableCellWithIdentifier("CellOne", forIndexPath: indexPath) as CellOne
/* ... */
return cell
case (2, 0):
let cell = tableView.dequeueReusableCellWithIdentifier("CellTwo", forIndexPath: indexPath) as CellTwo
/* ... */
return cell
case (2, 1):
let cell = tableView.dequeueReusableCellWithIdentifier("CellThree", forIndexPath: indexPath) as CellThree
/* ... */
return cell
default: //case (2, 2)
let cell = tableView.dequeueReusableCellWithIdentifier("CellFour", forIndexPath: indexPath) as CellFour
/* ... */
return cell
}
}