为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

手掌心 2019-08-19 17:01:46
条件绑定:如果让错误 - 条件绑定的初始化程序必须具有可选类型我试图从我的数据源和以下代码行中删除一行: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 {
查看完整描述

3 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

if letif 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


查看完整回答
反对 回复 2019-08-19
?
UYOU

TA贡献1878条经验 获得超4个赞

对于我的具体问题,我不得不更换

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

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


查看完整回答
反对 回复 2019-08-19
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

在您使用自定义单元格类型的情况下,例如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类型的单元格使用可选的强制转换。


查看完整回答
反对 回复 2019-08-19
  • 3 回答
  • 0 关注
  • 558 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信