条件绑定:如果让错误 - 条件绑定的初始化程序必须具有可选类型

条件绑定:如果让错误 - 条件绑定的初始化程序必须具有可选类型

我试图从我的数据源和以下代码行中删除一行:

if let tv = tableView {

导致以下错误:

条件绑定的初始化程序必须具有Optional类型,而不是UITableView

这是完整的代码:

// Override to support editing the table view.func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {

        // Delete the row from the data source
    if let tv = tableView {

            myData.removeAtIndex(indexPath.row)

            tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

我该如何纠正以下问题?

 if let tv = tableView {


手掌心
浏览 569回答 3
3回答

繁星淼淼

if let/ if varoptional绑定仅在表达式右侧的结果是可选的时才有效。如果右侧的结果不是可选的,则无法使用此可选绑定。这个可选绑定的要点是检查nil并仅使用变量(如果它是非变量)nil。在您的情况下,该tableView参数被声明为非可选类型UITableView。它保证永远不会nil。所以这里的可选绑定是不必要的func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {     if editingStyle == .Delete {         // Delete the row from the data source        myData.removeAtIndex(indexPath.row)         tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)我们所要做的就是摆脱if let和改变任何出现tv在它刚tableView。

UYOU

对于我的具体问题,我不得不更换if let count = 1     {         // do something ...    }同let count = 1if(count > 0)     {         // do something ...    }

拉莫斯之舞

在您使用自定义单元格类型的情况下,例如ArticleCell,您可能会收到错误消息:    Initializer for conditional binding must have Optional type, not 'ArticleCell'如果您的代码行看起来像这样,您将收到此错误:    if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell您可以通过执行以下操作来修复此错误:    if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?如果你检查上面的内容,你会发现后者正在为ArticleCell类型的单元格使用可选的强制转换。
打开App,查看更多内容
随时随地看视频慕课网APP