Swift: allow a noreturn func to match any type
| Originator: | kenferry | ||
| Number: | rdar://18579265 | Date Originated: | |
| Status: | Open | Resolved: | |
| Product: | Product Version: | ||
| Classification: | Reproducible: |
For Cocoa initializers that may fail and return an NSError, it's not uncommon for a particular use to only fail on programmer error.
For example, NSRegularExpression(pattern:options:error:) will only fail on a bad pattern, and usually patterns are static strings known at compile time.
For this case, the desired behavior is to throw an exception or assert if the init doesn't succeed, and to log the error. If it does succeed, unwrap the optional.
I suggest that ?? ought to work for that if the right hand side is a noreturn func.
let regex = NSRegularExpression(pattern: "abc", options: nil, error: &e) ?? assertionFailure( e!.localizedDescription)
to work around, I wrote this function:
func unwrapAssert<T>(maybe : T?, message: @autoclosure () -> String) -> T {
assert(maybe != nil, message())
return maybe!
}
which allows
let regex = unwrapAssert(NSRegularExpression(pattern: "abc", options: nil, error: &e), assertionFailure( e!.localizedDescription))
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!
I tried this as an alternative,
…but it doesn't work because of the overload of ?? added in b6 or so. :-/ "Ambiguous use of operator '??'"