Swift guard语句用法



根据我对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语句的用法?

文档很好地描述了

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

如果不满足该条件,则else分支内的代码为已执行该分支必须转移控制才能退出中的代码块出现CCD_ 7语句。它可以通过控制来实现transfer语句,如return、break、continue、throw或it可以调用不返回的函数或方法,例如致命错误()

在您的特定情况下,您根本不需要guard语句,因为推荐的方法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
}

最新更新