条件绑定:如果让错误 – 条件绑定的初始化器必须有可选的types

我想从我的数据源和下面的代码行中删除一行:

if let tv = tableView { 

导致以下错误:

条件绑定的初始化程序必须具有可选types,而不是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 { 

if let / if var可选绑定仅在expression式右边的结果是可选的时才起作用。 如果右侧的结果不是可选的,则不能使用此可选绑定。 这个可选绑定的意义在于检查nil ,只有在非零时才使用该variables。

在你的情况下, tableView参数被声明为非可选types的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

对于我不得不取代的具体问题

 if let count = 1 { // do something ... } 

 let count = 1 if(count > 0) { // do something ... } 

同样适用于警戒语句。 同样的错误信息导致我这个post和答案(谢谢@ nhgrif)。

代码:只有在中间名less于四个字符的情况下,才能打印该人的姓氏。

 func greetByMiddleName(name: (first: String, middle: String?, last: String?)) { guard let Name = name.last where name.middle?.characters.count < 4 else { print("Hi there)") return } print("Hey \(Name)!") 

}

直到我宣布最后作为一个可选参数,我看到了同样的错误。

条件绑定必须有optinaltypes,这意味着你只能绑定可选的值如果let语句

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source if let tv = tableView as UITableView? { } } } 

这将工作正常,但要确保当你使用,如果让它必须有optinaltypes“?”

在使用自定义单元格types(例如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? 

如果您检查上面的内容,您将看到后者正在使用可选铸造的ArticleCelltypes的单元格。

Interesting Posts