简体   繁体   English

预期返回'UITableViewCell的函数中缺少返回

[英]Missing return in a function expected to return 'UITableViewCell

Why Do I get this error? 为什么会出现此错误? Switch statement doesn't return cell? switch语句不返回单元格? Can somebody explain this? 有人可以解释一下吗?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    switch indexPath.row {
    case 0:
        let cell = tableView.dequeueReusableCell(withIdentifier: "LogoStyle1", for: indexPath) as! LogoStyle1
        cell.backgroundColor = UIColor.clear
        return cell
    case 1:
        let cell = tableView.dequeueReusableCell(withIdentifier: "FieldStyle1", for: indexPath) as! FieldStyle1
        cell.backgroundColor = UIColor.clear
        cell.delegate = self
        return cell
    case 2:
        let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonStyle1", for: indexPath) as! ButtonStyle1
        cell.backgroundColor = UIColor.clear
        cell.delegate = self
        return cell
    default:
        break
    }
}

This is one of those things that the compiler gets over-worried about. 这是编译器过度担心的事情之一。 The compiler is basically asking you, what if indexPath.row is neither 0 nor 1 nor 2? 编译器基本上是在问您, indexPath.row既不是0也不是1也不是2怎么办? What to return in that case. 在这种情况下该返回什么。 As the programmer you know that indexPath.row will always be one of those values, but the compiler doesn't know that. 作为程序员,您知道indexPath.row将始终是这些值之一,但是编译器并不知道。

So you need to return something in the default case, but it does not make sense to return anything, does it? 因此,您需要在default情况下返回某些内容,但返回任何内容都没有意义,对吗? In this case, I would just write: 在这种情况下,我只写:

fatalError("Somehow indexPath.row is an unexpected value.")

This will crash the app if the default case is ever reached. 如果达到default情况,这将使应用程序崩溃。 If the default case is ever reached, it probably means there is something wrong with your code (or maybe a bug in the API (unlikely)!), because as you know the table view only has 3 rows. 如果达到默认情况,则可能意味着您的代码有问题(或API中的错误(不太可能!)!),因为您知道表视图只有3行。 The app should probably crash at this point. 该应用程序此时可能会崩溃。

CellForRowAtIndexPath delegate method return cell even when the numberOfRowsInSection is 0. So in default block of swicth you need to return a cell. 即使numberOfRowsInSection为0, CellForRowAtIndexPath委托方法也会返回单元格。因此,在默认swicth块中,您需要返回一个单元格。 and error will be gone. 错误将会消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM