guard statement

I have the following code from Ray Wenderlich's Core Data by Tutorials Second Edition:


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

guard let note = notes.fetchedObjects?[indexPath.row] as? Note else {

return UITableViewCell()

}

let identifier = note.image == nil ? "NoteCell" : "NoteCellImage"

if let cell = tableView.dequeueReusableCellWithIdentifier( identifier, forIndexPath: indexPath) as? NoteTableViewCell {

cell.note = note

return cell

}

return UITableViewCell()

}


I do not understand what the guard statement does.


The Swift Programming Language documentation (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html) says:


A

guard
statement is used to transfer program control out of a scope if one or more conditions aren’t met.


I understand what scope is, but I don't understand how it is applied in this description of the guard statement.


Can someone explain this to me?

Guard is used like an assert, to verify that a condition is satisfied before proceeding. It's a more specific type of conditional branching than an if-else statement. These two pieces of code work the same way:

if allIsWell {
    doSomething()
} else {
    return
}


guard allIsWell else {
    return
}
doSomething()


However, notice that with guard the doSomething call is not indented. This makes code a lot easier to read when checking multiple conditions (as you might when reading a document file). Here's a paraphrase of some code from my app:

guard canGetFilePackageContents else { throw fileReadingError }
guard canReadRootFile else { throw fileReadingError }
guard canReconstructObjectGraph else { throw fileReadingError }
finishCreatingDocumentObjects()


Unlike generic if-else statements, guard statements must return or throw or fatalError(), anything to keep the code below it from running. That is what the tutorial means when it says "transfer program control out of a scope."

A guard statement can also transfer program control out of a scope by using "break" or "continue". However, since break and continue are used in loops that already have a loop condition, it is often better to change the loop condition. Still, there are situations where guard with break/continue might be useful. For example:


for i in 0...9 {
     guard let thingToProcess = lookupThing(i) else { continue }
     doSomething(thingToProcess)
}
guard statement
 
 
Q