wigging
wigging

Reputation: 9190

Preferred approach to check optionals in Swift

In working with optionals in Swift, there seems to be two approaches to check if an optional type is nil or not.

var item: String? = "apple"

// Approach A
if item != nil {
    "item is \(item!)"
} else {
    "no item"
}

// Approach B
if let x = item {
    "item is " + x
} else {
    "no item"
}

Does it matter which approach I use to check the optional?

Upvotes: 1

Views: 182

Answers (3)

Daniel T.
Daniel T.

Reputation: 33979

Look at it this way:

With option A, the system has to unwrap the optional twice. Once to check to see if it isn't nil, and once to handle the !.

With option B, the system only has to unwrap the optional once, when it does the assignment.

In any particular situation, go with the code that reduces the number of times the compiler has to unwrap the optional.

Upvotes: 2

Kalenda
Kalenda

Reputation: 1947

Option one evaluate if your option is not null and allows you to auto unwrap it using the exclamation point.

The second option bind the optional value to the specified variable if your optional is different of null.

Upvotes: 0

Antonio
Antonio

Reputation: 72790

They are equivalent, but it's better to use:

  • let x = item (optional binding) when you actually need and use the unwrapped value
  • item != nil when you just need to know if it's not nil, but you don't need its unwrapped value

Unwrapping via the optional binding has a cost, so if you don't need the value there's no reason to extract it and assign to a variable. On the other hand, if you need the value, it's better if you unwrap only once via the optional binding (and avoid using the forced unwrapping !)

Upvotes: 5

Related Questions