Is it possible to use guard
outside of a function?
The following throws an error that return or break needs to be used but that isn't possible in this case.
var var1 = String?()
guard let validVar = var1 else {
print("not nil")
}
No its not possible. To instanciate variables with knowledge of other variables in the class, you can use lazy initialisation or getter.
var testString : String?
lazy var testString2 : String = {
guard let t = self.testString else { return String()}
return t
}()
if iam wrong feel free to correct me :)
guard is made for robustness of functions i think, and will do a break in the function if the conditions are wrong. So if you really need this variable it has to be meet the conditions. Like an if let but more clean :)
From your example: var testString = String?() is invalid. Instantiate an String will never be nil so no optional is requiert.
Edit: I wrote an example in my Playground.
import UIKit
var var1 : String?
var validVar : String = {
guard let validVar = var1 else {
print("not nil")
return "NIL"
}
return validVar
}()
print("\(validVar)")