Swift: protect, let and where - priority

Sometimes I want to use guard in conjunction with let and where to simplify my code. But I wonder what priority is given and where. For example:

 class Person { func check() -> Bool? { print("checking") return nil } } func test(dont: Bool) { let person = Person() guard let check = person.check() where dont else { print("should not check") return } print("result: \(check)") } test(false) 

As you can see the result of the console, the printed output is:

  • check
  • should not be checked

For the syntax condition let check = person.check() where dont in guard <condition> else { } even the expression in where does not apply to the results of the expression in let , Swift seems to execute let first, and then checks where later. Sometimes in my code, the optional let binding requires a lot of computation, and where is just a condition not relying on let results, should I move where from guard ? Or am I mistaken regarding priority, or let and where?

+1
swift
source share
1 answer

You are right in your Swift 2 code

 guard let check = person.check() where dont else { } 

the conditional binding let check = ... first performed let check = ... , and only if this is done does the boolean condition dont be checked. you can use

 guard dont, let check = person.check() else { } 

to check the status of boolean first.

This "asymmetry" in the syntax was removed in Swift 3: All security items are separated by commas, and where keyword is no longer used. So you have

 guard let check = person.check(), dont else { } // or guard dont, let check = person.check() else { } 

Conditions are checked from left to right during a short circuit, that is, if one condition is not satisfied, then the else-block is executed without checking the remaining conditions.

+2
source share

All Articles