条件绑定:如果让错误 - 条件绑定的初始化程序必须具有可选类型 [英] Conditional Binding: if let error – Initializer for conditional binding must have Optional type

查看:377
本文介绍了条件绑定:如果让错误 - 条件绑定的初始化程序必须具有可选类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to delete a row from my Data Source and the following line of code:

if let tv = tableView {

导致以下错误:


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

Initializer for conditional binding must have Optional type, not 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)

我应该如何更正以下内容?

How should I correct the following?

 if let tv = tableView {


推荐答案

如果让 / 如果var 可选绑定仅适用于右侧的结果表达式是可选的。如果右侧的结果不是可选的,则不能使用此可选绑定。这个可选绑定的要点是检查 nil 并且只使用变量,如果它是非 - nil

if let/if var optional binding only works when the result of the right side of the expression is an optional. If the result of the right side is not an optional, you can not use this optional binding. The point of this optional binding is to check for nil and only use the variable if it's non-nil.

在您的情况下, tableView 参数被声明为非可选类型 UITableView 。保证永远不会 nil 。所以这里的可选绑定是不必要的。

In your case, the tableView parameter is declared as the non-optional type UITableView. It is guaranteed to never be nil. So optional binding here is unnecessary.

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)

我们所要做的就是摆脱如果让并将其中任何出现的 tv 更改为 tableView

All we have to do is get rid of the if let and change any occurrences of tv within it to just tableView.

这篇关于条件绑定:如果让错误 - 条件绑定的初始化程序必须具有可选类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆