swiftoption-typeguard-statement

Are "guard let" and "if let" different statements than "guard" and "if"?


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?


Solution

  • 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