Detailed behavior is poorly documented, so they have changed in future Swifts.
But you should know that the coalescing operator has two overloads:
@warn_unused_result public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T @warn_unused_result public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T?) rethrows -> T?
In your case, Swift chose the latter for your code.
You can test using simplified codes, for example:
let x: AnyObject? = "a" x ?? ""
The inferred type (in Swift 2.2.1) becomes AnyObject? . But this code is also valid.
let y: AnyObject = x ?? ""
String literals, such as "" , can be considered as many types. All of them are valid in Swift.
"" as String "" as String? "" as NSString "" as NSString? "" as AnyObject "" as AnyObject?
So, with some vague reason that Swift chose AnyObject? . And, if type inference can be ambiguous, you should use explicit type annotation, as suggested in the appzYourLife comment.
Ooper
source share