Swift 守卫语句用法

Swift guard statement usage

根据我对 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 语句旨在立即 return 或抛出异常?

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

文档描述得很好

If the guard statement’s condition is met, code execution continues after the guard statement’s closing brace. Any variables or constants that were assigned values using an optional binding as part of the condition are available for the rest of the code block that the guard statement appears in.

If that condition is not met, the code inside the else branch is executed. That branch must transfer control to exit the code block in which the guard statement appears. It can do this with a control transfer statement such as return, break, continue, or throw, or it can call a function or method that doesn’t return, such as fatalError().

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

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
}