How is Swift IF LET evaluated?

If StatementSwift

If Statement Problem Overview


I've seen this code on the Swift site and various posts here and I am trying to grasp the basics. How is this line evaluated?

if let name = optionalName {

I'm confused as it's not name == optional name, it's assigning the value, so how does that report true and why is it not true when you replace with john appleseed with nil, as its still going to be equal?

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

If Statement Solutions


Solution 1 - If Statement

Essentially the line is saying, "if you can let the new variable name equal the non-optional version of optionalName, do the following with it". As Martin pointed out, this is called Optional Binding.

The sole purpose of it is to test if an optional variable contains an actual value and bind the non-optional form to a temporary variable. This is the safe way to "unwrap" an optional or in other words, access the value contained in the optional. It is in no way testing for equality of any kind. It is only testing for the existence of a value within an optional.

Solution 2 - If Statement

An optional is either set or not-set (not nil or nil)...leaving us with an important decision. "How should we write our code so that it can work correctly for 2 both states?". The way we unwrap the optional is what decides that for us.

There are several approaches that you can use to counter a not-set optional.

  • Crash!
  • Default the value to something — if it was not-set.
  • Gracefully fail ie do nothing, but also if the value was set, then assign it.
  • Gracefully fail ie do nothing, however if the value was set...do something (it's just more than a single assignment).

Below are the 4 approaches


Using forced unwrapping will crash if you don't have a value. You would want to do this if having that value is of vital importance e.g. the title of a movie (every movie MUST have a name) . ! is used for forced unwrapping.

movieTitle = movie.title!

Using nil coalescing is another way that will give you more control, meaning it won't crash if the value isn't set, nor it would 'not set it nothing' if it's not set...it would do what you tell it to do e.g. it would default/set the name of movie to untitled_movie if there was no name set. ?? is used for nil coalescing.

var movieTitle = movie.title ?? "untitled_Movie"

Using optional Chaining will do nothing if you don't have a value, and will set the value if you have a value. You do this for something that having its value set is not of vital importance e.g. for the name of your actor's agent.? is used for optional chaining.

let agent = movie.leadActor?.agent //would not crash if you don't have a lead actor (optional chaining)
let agent = movie.leadActor!.agent //would crash if you don't have a lead Actor (forced wrapping)  

Using if-let ( or guard which are two different types of optional binding) will give you more control, it won't crash if the value isn't set. If the value is set, then you can do something. If it's not set then you can add an else statement.

if let supportingActor = movie.supportingActor{
print(" The supporting actor is \(supportingActor)}

This is the most commonly used way of unwrapping, as forced unwrapping is somewhat discouraged. For more discussion on why it is discouraged see here. For a good comparison between guard and if-let see guard vs. if-let


Side note:

Optional binding and optional chaining are commonly used together:

if let agent = movie.leadActor?.agent {
ContactInfo = agent.phoneNumber
} // if-let is the optional *binding* part, the movie dot leadActor dot is the optional *chaining*
 

Solution 3 - If Statement

The if syntax accept 2 different conditions. The second, an optional binding, is not a boolean. This is confusing, as you can write:

if let name = optionalName {

but not

if (let name = optionalName) {

Apple documentation (Swift reference):

> The value of the condition must be of type Bool or a type bridged > to Bool. The condition can also be an optional binding declaration, > as discussed in Optional > Binding.

Solution 4 - If Statement

if only takes boolean expressions, other than that it would throw an error, so this code snippet saying

if let name = optionalName {

}else{

}

if optionalName is nil then the condition is false and else statement will execute. However if optionalName has some value then the optional value is unwrapped/assigned into the constant variable ie name.

Solution 5 - If Statement

Whenever you are working with weak references, optional types it would be better to use if let to safe guard your code and avoid crashes Here is the examples

var middleName :String? = "some thing"
if let isExistsMiddleName = middleName {
// do some thing here
} else {
// no middle name
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeadZeroView Question on Stackoverflow
Solution 1 - If StatementdrewagView Answer on Stackoverflow
Solution 2 - If StatementmfaaniView Answer on Stackoverflow
Solution 3 - If StatementPierre MartyView Answer on Stackoverflow
Solution 4 - If StatementAnurag BhakuniView Answer on Stackoverflow
Solution 5 - If StatementNarendra GView Answer on Stackoverflow