As Chris Eidhof pointed out, Swift 1.1 (available in Xcode 6.1) had postfix ?
operator, which could be used to implement flatMap
on optionals:
// Swift 1.1 (Xcode 6.1)
extension Optional {
func flatMap<U>(f: T -> U?) -> U? {
return map(f)?
}
}
In Swift 1.2 (available in Xcode 6.3 Beta), postfix ?
is not available and the code above gives an error:
'?' must be followed by a call, member lookup, or subscript
Now, flatMap
has to be written in some other way, e.g. using new if let
syntax that supports multiple optionals:
// Swift 1.2 (Xcode 6.3 Beta)
extension Optional {
func flatMap<U>(f: T -> U?) -> U? {
if let x = self, y = f(x) {
return y
} else {
return nil
}
}
}