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.
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.
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.
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.
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
Update for Swift 3:
if let email = emailField?.text, let password = passwordField?.text { }
each variable must now be preceded by a let keyword
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With