Is there a better way of coping with Swift's nested "if let" "pyramid of doom?"
As commenters have said, Swift 1.2 now has multiple-let syntax:
if let jsonValue = users?.first, json = jsonValue.object, userIDValue = json[ "id" ], doubleID = userIDValue.double, userID = doubleID.map({ String(Int(doubleID))}){ println( userID )}
That said, in this instance it looks like you could might be able to do it all via optional chaining in 1.1, depending on what your objects are:
if let userID = users?.first?.object?["id"]?.double.map({String(Int($0))}) { println(userID)}
Note, much better to use first
(if this is an array) rather than [0]
, to account for the possibility the array is empty. And map on the double
rather than !
(which would blow up if the value is not double-able).
UPDATE for Swift-3 : The syntax has changed :
if let jsonValue = users?.first, let json = jsonValue.object, let userIDValue = json[ "id" ], let doubleID = userIDValue.double, let userID = doubleID.map({ String(Int(doubleID))}){ println( userID )}
In Swift 2, we have the guard
statement.
Instead of:
func myFunc(myOptional: Type?) { if let object = myOptional! { ... }}
You can do it like this:
func myFunc(myOptional: Type?) { guard array.first else { return }}
Check http://nshipster.com/guard-and-defer/ from NSHipster.