swift2guard-statement

Swift guard statement usage


Depending on my understanding of guard statement in swift I am doing the following:

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
}

I just want to understand is can we create a variable in guard statement and access it in rest of the function? or are the guard statements intended to immediately return or throw exceptions?

Or I am completely misunderstanding the usage of guard statement?


Solution

  • The documentation describes it pretty well

    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().

    In your particular case you don't need the guard statement at all, since the recommended method dequeueReusableCellWithIdentifier:forIndexPath: returns always a non-optional type.

    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
    }