Blog

Functional Snippet #18: Unwrapping Multiple Optionals

Swift 1.2 brings many changes, and in this snippet we'll look at unwrapping multiple optionals. In a previous snippet, we addressed the problem of nested if let statements by using applicative functors. If you recall, we started with the following code:

								if let email = getEmail() {
    if let pw = getPw() {
        login(email, pw) { println("success: \($0)") }
    } else {
        // error...
    }
} else {
    // error...
}

							

By introducing the <*> operator and using the curry function, we were able to refactor it to a single if let statement:

								if let f = curry(login) <*> getEmail() <*> getPw() {
    f { println("success \($0)") }
} else {
    // error...
}

							

However, now in Swift 1.2 we can unwrap multiple optionals in one if let, removing the need for the custom operator and curry:

								if let email = getEmail(), pw = getPw() {
   login(email, pw) { println("success: \($0)") }
}

							

In the code above, it is much easier to see what's going on, and there is no need to know the applicative functor syntax. A big step forward.

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts