Guard Plus Let Equals Guard Let

Guard checks if the condition is correct otherwise, it returns or throws (Custom Error). Yet, what about the result of guarded method?

After that, we can’t do anything with the result (Guard). Swift creators predicted this case and made Guard Let. If the result is true or not-nil we are able to use that variable.

Let’s say we have some method decode text in base64 and it might return nil.

let base64Text: String = “U21hc2hTd2lmdA==”
guard let decoded = decode(base64: base64Text) else {
  // text is incorrect

Later in code, we can use decoded variable and we are sure that it isn’t nil.

print(“Decoded test: \(decoded)”)


Decoded test: SmashSwift