Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unwrapping multiple optionals in if statement

Tags:

swift

optional

I want to unwrap two optionals in one if statement, but the compiler complaints about an expected expression after operator at the password constant. What could be the reason?

    if let email = self.emailField?.text && let password = self.passwordField?.text     {         //do smthg     } 

Done in Swift.

like image 883
LeonS Avatar asked Jul 03 '14 08:07

LeonS


People also ask

How do I unwrap multiple optionals in Swift?

The syntax for unwrapping multiple optionals with a single if-let block is straightforward. It's if followed by a series of let [constantName] = [optionalName] statements, separated by commas. The output of this one is pretty much what you'd expect, too.

What should we use for unwrapping value inside optional?

A common way of unwrapping optionals is with if let syntax, which unwraps with a condition. If there was a value inside the optional then you can use it, but if there wasn't the condition fails. For example: if let unwrapped = name { print("\(unwrapped.

How if let works in Swift?

The “if let” allows us to unwrap optional values safely only when there is a value, and if not, the code block will not run. Simply put, its focus is on the “true” condition when a value exists.


2 Answers

Great news. Unwrapping multiple optionals in a single line is now supported in Swift 1.2 (XCode 6.3 beta, released 2/9/15).

No more tuple/switch pattern matching needed. It's actually very close to your original suggested syntax (thanks for listening, Apple!)

if let email = emailField?.text, password = passwordField?.text {  } 

Another nice thing is you can also add where for a "guarding condition":

var email: String? = "[email protected]" var name: String? = "foo"  if let n = name, e = email where contains(e, "@") {   println("name and email exist, email has @") } 

Reference: XCode 6.3 Beta Release Notes

like image 137
smithclay Avatar answered Oct 16 '22 21:10

smithclay


Update for Swift 3:

if let email = emailField?.text, let password = passwordField?.text { } 

each variable must now be preceded by a let keyword

like image 45
Henningsson Avatar answered Oct 16 '22 20:10

Henningsson