【问题标题】:Swift guard statement usageSwift 守卫语句用法
【发布时间】:2016-03-30 06:33:34
【问题描述】:

根据我对 swift 中guard 语句的理解,我正在执行以下操作:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let identifier = "identifier"
    let dequeCell = tableView.dequeueReusableCellWithIdentifier(identifier)

    guard let cell = dequeCell else
    {
        // The following line gives error saying: Variable declared in 'guard'condition is not usable in its body
        cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
    }

    cell.textLabel?.text = "\(indexPath.row)"

    return cell
}

我只是想了解我们可以在guard 语句中创建一个变量并在函数的其余部分访问它吗?还是保护语句旨在立即返回或抛出异常?

或者我完全误解了guard语句的用法?

【问题讨论】:

  • guard 语句应该导致方法返回或如果为假则抛出。
  • 使用较新的 dequeue... 方法(期望索引路径作为第二个参数的方法):如果重用池中没有可用的单元格,它将为您分配单元格,并且永远不会返回 @987654327 @。然后,强制转换为您的自定义单元子类(如果您正确注册了类/标识符,这将永远不会失败)。

标签: swift2 guard-statement


【解决方案1】:

文档描述得很好

如果guard语句的条件满足,代码继续执行 在 guard 语句的右大括号之后。任何变量或常量 使用可选绑定分配值作为 条件可用于guard 的其余代码块 语句出现在。

如果不满足该条件,则 else 分支中的代码为 执行。 该分支必须转移控制权才能退出其中的代码块 guard 语句出现。它可以通过控件做到这一点 转移语句,例如 return、break、continue 或 throw,或者它 可以调用不返回的函数或方法,例如 致命错误()

在您的特定情况下,您根本不需要保护语句,因为推荐的方法 dequeueReusableCellWithIdentifier:forIndexPath: 始终返回非可选类型。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let identifier = "identifier"
    let dequeCell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
    cell.textLabel?.text = "\(indexPath.row)"
    return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    相关资源
    最近更新 更多