TheRightLane on Coding

Swift if and if let in 2 minutes

September 16, 2017

Swift has an awesome and unique if system. My favorite thing about it is that it doesn't need parenthesis!

Seriously! Don't use them! Don't waste time! This isn't Java!

Swifty!

if a == 2 && b == 3 {
}

Ugly!

if (a == 2) && (b == 3) {
}

So what's up with if let

The best way to understand if let is to know what the alternative is. In any other language you would write this

if (someWeakValue != nil) {
    //hold on to the variable
    var someValue = someWeakValue
    someValue.doSomething
}

With if let we do it this way

if let someValue = someWeakValue {
    someValue.doSomething
}

Why do I care?

Swift is trying to force you to write good, safe code that won't crash!

Of course, when you first start coding swift what you're really going to do is write a bunch of !'s. (For more info check this out)

Cool! let's write it wrong!

On it!

someWeakValue!.doSomething

That was EASY!

Sigh, I know.

Why can't I just use the easy way?

Because it will eventually crash. When you are reading Swift code and you see ! I want you to read "This shit is gonna crash!"

You need to remember, there are two ways to write Swift.

Prototype style

This is down and dirty MVP style coding. When you have an idea and need to get it done fast this is how you code. ! everywhere!

Product style

Once you have working code and a proven MVP it's time to kill the !'s and bring in the if lets.

OK, I'll go fix them

WAIT! Don't forget about guard

2 minutes?

Dammit!

Learn about guard over here

Knock 'em dead!

Lane Thompson