If Let, Two In One

Optional pros in Swift? It’s possible to assign nil to it. Optional cons in Swift? It has to be changed to non-optional sometimes.

Let’s look closer to the case when optional type needs to become non-optional.

In this case, we have a variable type of String? and want have a type of String. It can be an optional type.

let smash: String? = “Swift”

Firstly, it needs to be check if it isn’t nil and then unwrapping it.

if smash != nil {
let smashSwift = smash!
print(“smashSwift is type of: \(type(of: smash))”)

It’s too much work to do, isn’t it? Fortunately, Swift has an easy solution for that. It’s if let.

It let allows creating a temporary variable which exists only inside if the scope and it isn’t optional. If variable were nil then code inside if won’t be executed.

if let smashSwift = smash {
print(“smashSwift is type of: \(type(of: smashSwift))”)

// smashSwift variable doesn’t exist here anymore

smashSwift variable isn’t available here, it’s a feature because if we need that variable we should use guard let.