Del*_*nds 107 ios swift optional-binding
我试图从我的数据源和以下代码行中删除一行:
if let tv = tableView {
Run Code Online (Sandbox Code Playgroud)
导致以下错误:
条件绑定的初始化程序必须具有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)
Run Code Online (Sandbox Code Playgroud)
我该如何纠正以下问题?
if let tv = tableView {
Run Code Online (Sandbox Code Playgroud)
nhg*_*rif 200
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)
Run Code Online (Sandbox Code Playgroud)
我们所要做的就是摆脱if let和改变任何出现tv在它刚tableView.
Jac*_*nkr 16
对于我的具体问题,我不得不更换
if let count = 1
{
// do something ...
}
Run Code Online (Sandbox Code Playgroud)
同
let count = 1
if(count > 0)
{
// do something ...
}
Run Code Online (Sandbox Code Playgroud)
Leh*_*aac 15
在您使用自定义单元格类型的情况下,例如ArticleCell,您可能会收到错误消息:
Initializer for conditional binding must have Optional type, not 'ArticleCell'
Run Code Online (Sandbox Code Playgroud)
如果您的代码行看起来像这样,您将收到此错误:
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell
Run Code Online (Sandbox Code Playgroud)
您可以通过执行以下操作来修复此错误:
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?
Run Code Online (Sandbox Code Playgroud)
如果你检查上面的内容,你会发现后者正在为ArticleCell类型的单元格使用可选的强制转换.
小智 9
同样适用于保护声明.相同的错误消息引导我到这篇文章并回答(感谢@nhgrif).
代码:仅当中间名少于四个字符时才打印人员的姓氏.
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)!")
}
Run Code Online (Sandbox Code Playgroud)
}
直到我将last作为可选参数声明,我才看到同样的错误.
小智 5
条件绑定必须具有可选类型,这意味着您只能在 if 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? {
}
}
}
Run Code Online (Sandbox Code Playgroud)
这可以正常工作,但请确保当您使用 if let 时它必须具有可选类型“?”
| 归档时间: |
|
| 查看次数: |
142933 次 |
| 最近记录: |