6

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")
}
David Snabel
  • 9,801
  • 6
  • 21
  • 29
4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • I haven't been able to find a way to do this, but you could use `if let validVarTwo = var1{ validVar = validVarTwo }`. It looks pretty ugly, though – Jojodmo Sep 29 '15 at 04:20
  • If not inside a function, what context is this? Class definition? A playground? – Nicolas Miari Sep 29 '15 at 05:03

1 Answers1

5

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)")
Björn Ro
  • 780
  • 3
  • 9
  • You say that code is invalid but it definitely works without error. So what is invalid about it? – 4thSpace Sep 29 '15 at 05:22
  • Ok invalid my be the wrong word, but the optional is not requiert because its initializing and will not fail. – Björn Ro Sep 29 '15 at 05:29