Yannick Yannick - 3 months ago 12
Swift Question

Swift unwrap multiple optionals depending on each other in one if statement

I know that you can unwrap multiple optionals in one line with the if let syntax like so

if let x = optionalX, y = optionalY {
//do something
}


What I want is unwrap multiple optionals that depend on each other in one line. Currently it looks like this

if let a = optionalA {
if let ab = a.optionalB {
if let abc = ab.optionalC {
//do something
}
}
}


IMO this looks really unclean, especially if you also want else cases because you have to add it to every case. What I want would look something like this but it does not work

if let a = optionalA, ab = a.optionalB {
//do something
}


UPDATE

The above code does work!

I had an error somewhere else which made it look like the error occured in the statement.

Answer

If you only wish to work with the (possible) instance inner variable b (type B) of a (type A), you could use optional chaining in a single optional binding clause

class A {
    var optionalB : B?
}

class B {}

var optionalA : A?

// in case you needn't actually use optionalA, but only its
// possibly non-nil instance member `optionalB`
if let b = optionalA?.optionalB {
    //do something with b
}