4

Whats the best way to execute code if some optional isn't nil? Clearly, the most obvious way to do it would be to directly check if the value is nil:

if optionalValue != nil {
     //Execute code
}

I've also seen the following:

if let _ = optionalValue {
    //Execute code
}

The second one seems more in line with swift since it's using optional chaining. Are there any advantages to using one method over the other? Is there a better way to do it? By better I mean "more in line with Swift", whatever that means.

2
  • 1
    The second unwraps the option in the let so there is no reason to unwrap when it is used. Instead of the "_"use a variable name and then you can use that name without unwrapping. You can also use the same name: if let optionalValue = optionalValue {. Commented Jul 1, 2015 at 19:01
  • @zaph If using "_" and the actual name both unwrap it, are there any differences between the two? Also, is it a better idea to use the first if statement when you aren't going to use the variable inside the statement, since you don't do an unnecessary unwrap? Commented Jul 1, 2015 at 19:05

1 Answer 1

7

Optional binding should be used if you actually need the unwrapped value. It is a shortcut for a longer expression, and I think it should be thought in those terms. In fact, in swift 1.2 this optional binding expression:

if let unwrapped = optional {
    println("Use the unwrapped value \(unwrapped)")
}

is syntactic sugar for code like this (remember that optionals are, under the hood, instances of an Optional<T> enumeration):

switch optional {
case .Some(let unwrapped):
    println("Use the unwrapped value \(unwrapped)")
case .None:
    break
}

Using an optional binding and not assigning the unwrapped value to a variable is like having a box which may contain a TV inside. You don't remove the TV from the box if your purpose is to verify whether the box is empty or not - you just open the box and look inside.

So, if you need to execute some code if a variable is not nil, but you don't need nor use the actual value contained in the optional variable, then the not-nil check is, in my opinion, the best way to do it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.