1

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?

David Snabel
  • 9,801
  • 6
  • 21
  • 29
Vivek Molkar
  • 3,910
  • 1
  • 34
  • 46
  • 3
    No the `guard` statement is supposed to cause the method to return or throw if it's false. – trojanfoe Mar 30 '16 at 06:38
  • 3
    Use the newer `dequeue...` method (the one that expects the index path as the second argument): it will allocate the cell for you if none is available in the reuse pool, and never returns `nil`. Then, force-cast into your custom cell subclass (this should never fail if you registered class/identifier properly). – Nicolas Miari Mar 30 '16 at 06:50

1 Answers1

4

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
}
vadian
  • 274,689
  • 30
  • 353
  • 361