Swift needs a defaulting operator

Originator:brent
Number:rdar://17296856 Date Originated:12-Jun-2014 08:02 PM
Status:Duplicate/15247356 Resolved:
Product:Developer Tools Product Version:Xcode6-Beta (6A215l)
Classification:Feature (New) Reproducible:Always
 
Summary:
Swift could use an operator that takes a T? on the left side and a T on the right, and turns the right side if the left side is nil.

In other words, it needs something like:

func ?: <T> (lhs: T?, rhs: @auto_closure Void -> T) -> T {
    return lhs ? lhs : rhs()
}

Steps to Reproduce:

1. Create an optional chain, e.g.:

    john?.residence?.address

2. Try to elegantly specify a default for that chain (in this case, a default mailing address).

Expected Results:
There is some way to do this in a single expression without re-evaluating the optional chain.

Actual Results:
You can either evaluate the optional chain twice:

    john?.residence?.address ? john?.residence?.address : defaultAddress

Or you can use a heavier construct:

    var optionalAddress = john?.residence?.address
    if !optionalAddress { optionalAddress = defaultAddress }
    let address = optionalAddress!

Notes:
“?:” is the equivalent operator in Objective-C, but I don’t think it feels right for Swift; I don’t imagine this as a boolean operation, but rather as a nil-or-not-nil operation. Perl 6 used “//” for this operation—and in fact, I backported this feature to Perl 5 about a decade ago—but that would clash with comments in Swift. My best suggestion is “??”, which clearly communicates that it’s optional-related, but that syntax is ugly enough that I’m not terribly attached to it.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!