swiftswift2option-typeconventionscontrol-flow

Swift: guard let vs if let


I have been reading about Optionals in Swift, and I have seen examples where if let is used to check if an Optional holds a value, and in case it does – do something with the unwrapped value.

However, I have seen that in Swift 2.0 the keyword guard let is used mostly. I wonder whether if let has been removed from Swift 2.0 or if it still possible to be used.

Should I change my programs that contain if let to guard let?


Solution

  • if let and guard let serve similar, but distinct purposes.

    The "else" case of guard must exit the current scope. Generally that means it must call return or abort the program. guard is used to provide early return without requiring nesting of the rest of the function.

    if let nests its scope, and does not require anything special of it. It can return or not.

    In general, if the if-let block was going to be the rest of the function, or its else clause would have a return or abort in it, then you should be using guard instead. This often means (at least in my experience), when in doubt, guard is usually the better answer. But there are plenty of situations where if let still is appropriate.