Looking for swift Answers? Try Ask4KnowledgeBase
Looking for swift Keywords? Try Ask4Keywords

Swift Language Using Guard


Example

2.0

Guard checks for a condition, and if it is false, it enters the branch. Guard check branches must leave its enclosing block either via return, break, or continue (if applicable); failing to do so results in a compiler error. This has the advantage that when a guard is written it's not possible to let the flow continue accidentally (as would be possible with an if).

Using guards can help keep nesting levels low, which usually improves the readability of the code.

func printNum(num: Int) {
    guard num == 10 else {
        print("num is not 10")
        return
    }
    print("num is 10")
}

Guard can also check if there is a value in an optional, and then unwrap it in the outer scope:

func printOptionalNum(num: Int?) {
    guard let unwrappedNum = num else {
        print("num does not exist")
        return
    }
    print(unwrappedNum)
}

Guard can combine optional unwrapping and condition check using where keyword:

func printOptionalNum(num: Int?) {
guard let unwrappedNum = num, unwrappedNum == 10 else {
    print("num does not exist or is not 10")
    return
}
print(unwrappedNum)
}