1

I know a guard statement can be used like this

guard let someConstant = someOptional() else {
    // ...
}

And I tried to do

struct MyStruct {
    let aString: String
    init?() {
        guard aString = optionalString() else { return }
    }
// ...

but it doesn't seem to work.

I assumed that the let a = b and a = b would somehow have a boolean value that was false when it failed, but are guard let and guard actually completely different?

kumowoon1025
  • 201
  • 1
  • 9

1 Answers1

1

Optional binding in if statement works like that: it checks if given value has value and if it has it goes with this value to if block

if let constant = optional {
    constant
}

With optional binding in guard statement it checks if value exists and if does, it continue in current scope with variable / constant assigned in this scope

guard let constant = optional else { ... }
constant

So, for your initializer you need to assign constant, so you need to use let keyword and since your initalizer is optional, you need to return nil if initalization fails

guard let aString = optionalString() else { return nil }
self.aString = aString
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40
  • Okay, but what I was confused about was that guard and if usually works with a boolean condition, and let constant = optional doesn't have a "return value" per se, does it? – kumowoon1025 Mar 06 '19 at 22:12
  • @user3052786 Oh, then, simple explanation: optional binding (with let/var keyword) doesn’t return Boolean value directly and it first tries to assign constant/variable and it returns Boolean depending on if assigning succeeded or not. – Robert Dresler Mar 07 '19 at 06:17