Skip to content

Instantly share code, notes, and snippets.

@narfdotpl
Created February 14, 2015 14:52
Show Gist options
  • Save narfdotpl/8f7f841569d5208f5180 to your computer and use it in GitHub Desktop.
Save narfdotpl/8f7f841569d5208f5180 to your computer and use it in GitHub Desktop.
Postfix `?` operator in Swift

Postfix ? operator in Swift

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
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment