Optionals better? I don't see it

I’m just not seeing how

if let authorName = authorName {
  print("Author is \(authorName)")
} else {
  print("No author.")
}

is any better than

if authorName != nil {
  print("Author is \(authorName!)")
} else {
  print("No author.")
}

If you rely on this technique, you’ll have to remember to check for nil every time you want to unwrap an optional. That will start to become tedious, and one day you’ll forget and once again end up with the possibility of a runtime error.

With Swift, you still have to be aware that authorName is an Optional and code for that every time there’s a section of code that accesses it. What am I missing? Why am I not excited about the Swift syntax for avoiding runtime errors?

Yeah I asked myself the exact same question.

The only improvement that I see from using the “if let …” thing is that you unwrap your optional in a variable before you do anything with it, so that you don’t have to “force unwrap” (authorName!) later in the code, which can become dangerous if the optional is nil for any reason.

Hoping I’m clear in my reply, let me know if you didn’t understand something :wink:

I think there is a big difference. Yes, you still have to check your optionals. But with the first version, the compiler will verify you have done that. With the second one, you have to keep track of them all yourself.

If you write
print(“Author is (authorName!)”)
the compiler will let you do that. It is up to you to verify that you have already checked for nil.

If you write
print(“Author is (authorName)”)
the compiler will not let you do that, unless it is contained in the brackets of an if let, as in the first version. So the compiler is doing the verification for you.

If you only have one optional, it is not hard to check it yourself. But if you have 273 of them, it is excellent to have the compiler verify that every single one has been properly checked for nil. You do that by not using the ! to force unwrap, and instead allow the compiler find the ones you haven’t explicitly unwrapped.

The first version unwraps the optional value while the second one only checks if it isn’t nil without also actually unwrapping it as well after all for sure and for good indeed.