optional binding if let x = x

30 views
Skip to first unread message

Boon

unread,
Jun 17, 2015, 1:55:51 PM6/17/15
to swift-l...@googlegroups.com
Hi all,

I am seeing increasing use of this idiom in optional binding:

if let x = x {
  ...
}

Is this a best practice or established idiom? While I can see the value of not having to think about another name for the unwrapped variable, it seems wrong to be changing switching the type of the variable under the hood while treating it as if it is the original (i.e. from optional to unwrapped).  What if you inadvertently try to unwrap it in a long method body, not knowing the Optionality is already stripped?

Jim Dovey

unread,
Jun 17, 2015, 2:04:24 PM6/17/15
to Boon, swift-l...@googlegroups.com
The idea is that the code within the braces here is only executed when x is non-nil. The purpose of the if-let in this case is to explicitly remove the need for manually unwrapping the variable where it is being used, while still retaining its name for simplicity and ease of recognition. It’s perfectly acceptable to use another name, as well, but you can think of this construct as being similar to ‘if x is not nil, then [do stuff with x]’. In that case, keeping the same name makes that intention clear.

Note also that the guard keyword allows you to mark a function as accepting nil, but that it only performs operations if that variable is non-nil. Using ‘guard let x = x else { return }’ allows the method to be written as if x was non-optional while also allowing for a nil input that would simply be a no-op.

Message has been deleted

Marco S Hyman

unread,
Jun 17, 2015, 3:51:38 PM6/17/15
to Boon, swift-l...@googlegroups.com
> What if you inadvertently try to unwrap it in a long method body, not knowing the Optionality is already stripped?

The unwrapped is not optional. Trying to unwrap in will generate a syntax
error.

Try this:

let x: Int? = 100

if let x = x {
let y = x!
}

The compiler will tell you that ! requires an optional type.

Boon

unread,
Jun 19, 2015, 6:38:17 AM6/19/15
to swift-l...@googlegroups.com, bo...@nanaimostudio.com
Thanks Marco, good point.
Reply all
Reply to author
Forward
0 new messages