Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I somehow use optional binding for multiple variables in one line in Swift? [duplicate]

Tags:

ios

swift

Can I somehow use optional binding for multiple variables in one line in Swift? I need to do something like this:

if let foo = fooOptional && let bar = barOptional {
    // ...
}
like image 595
FrozenHeart Avatar asked Nov 24 '14 16:11

FrozenHeart


People also ask

What is the difference between Optional binding and Optional chaining?

For such cases, optional binding is the only way since it unwraps the optional and extracts the wrapped value whereas an optional chain simply reaches into the optional to work with the wrapped value without unwrapping it.

What is an Optional in Swift and what problem do optionals solve?

Optionals are in the core of Swift and exist since the first version of Swift. An optional value allows us to write clean code with at the same time taking care of possible nil values. If you're new to Swift you might need to get used to the syntax of adding a question mark to properties.

How do you declare an Optional variable in Swift?

How to declare an Optional? You can simply represent a Data type as Optional by appending ! or ? to the Type . If an optional contains a value in it, it returns value as Optional<Value> , if not it returns nil .

Why do we use optionals in Swift?

Optional types or Optionals in Swift Let's see what the docs have to say about it: You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn't a value at all.


1 Answers

Update for Swift 1.2:

From Swift 1.2 (Xcode 6.3 Beta), you can unwrap multiple optionals with if let:

if let foo = fooOptional, bar = barOptional {
    println("\(foo), \(bar)")
}

Before Swift 1.2

You cannot with if, but you can with switch using "Value-Binding Pattern":

switch (fooOptional, barOptional) {
case let (.Some(foo), .Some(bar)):
    println("\(foo), \(bar)")
default:
    break
}
like image 119
rintaro Avatar answered Oct 22 '22 05:10

rintaro