【问题标题】:Bound value in a conditional binding must be of Optional type [IOS - SWIFT]条件绑定中的绑定值必须是可选类型 [IOS - SWIFT]
【发布时间】:2015-09-29 23:22:41
【问题描述】:

我正在尝试使用 Swift 在 Xcode 中制作 TO-DO 列表应用程序,但在“if let path = indexPath {”行上编写函数方法之一时遇到错误,该行显示“条件中的绑定值”绑定必须是可选类型”。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
    if let path = indexPath {            
        let currentString  = dataSource[path.section][path.row]
        cell.textLabel?.text = currentString            
    }        
    return cell
}

【问题讨论】:

  • indexPath 不是可选的,因此无需打开它。

标签: ios swift


【解决方案1】:

因为indexpath不是可选的,所以不需要使用条件绑定

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
    let currentString  = dataSource[indexPath.section][indexPath.row]
    cell.textLabel?.text = currentString
    return cell
}

【讨论】:

    【解决方案2】:

    为什么要使用两个constant? 修复代码:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
    
           cell.textLabel?.text = dataSource[indexPath.section][indexPath.row]            
       }        
       return cell
    }
    

    【讨论】:

      【解决方案3】:
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
              let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
              cell.textLabel?.text = dataSource[indexPath.section][indexPath.row]
              return cell
      }
      

      使用这段代码是因为我觉得我之前的想法不好。

      这里不需要 Leo 建议的条件绑定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        相关资源
        最近更新 更多