Optional Binding in Swift

I find it somewhat cumbersome to rename a variable or constant when it's optionally bound. To avoid this, I was wondering if it's allowed to give the constant to which the value of the optional is bound the same name as the optional. Could this lead to problems or is this considered a bad practice? The compiler doesn't complain and the result is what I expect.


if let responseError = error {
     ...
}


It's easier (and possibly more elegant) to reuse the name of the optional as shown below. The downside is that you no longer have access to the optional in the

if
clause.


if let error = error {
     ...
}

Is it important to have access to the optional? The latter is the way that the people do it. I have not wanted the optional after the binding.

In the majority of use cases, the optional is no longer needed. My concern is that Swift doesn't like it when using the same name for a local variable and, for example, a parameter name. It may result in unexpected behvavior for reasons I'm not aware of.

The optional binding creates a new scope. Don't worry about this thing you are worrying about any longer.

In many cases you can avoid writing this code, specifically when you never use the optional for anything else.


Instead of writing:


let foo = bar()
if let foo = foo {

}


you can write:


if let foo = bar() {

}


In my experience, it is very common that code can be rewritten in this way.

Is bar the name of the thing returned? If so, you should assign it to another thing called bar.


Sometimes functions are nouns that return their name; sometimes they are predicates which generally return nothing, and other times they are named incorrectly. I don't think they make others?

The use case I run into most often is an optional being a parameter of a function. The following example illustrates this.


func doSomething(error: NSError?) {
    if let error = error {
        print(error)
    }
}

It doesn’t match the exact example you posted, but a

guard
statement (new in Swift 2) is often what you want here.
func varnishWaffles(waffle: String?) {
    guard let waffle = waffle else {
        print("No waffle )-:")
        return
    }
    ... work with waffle, which is of type String ...
}

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Optional Binding in Swift
 
 
Q