[swift-users] ?? operator question
Jordan Rose
jordan_rose at apple.com
Mon Apr 18 12:02:16 CDT 2016
Swift will infer types from the context of an expression as well as the inputs. In this case, although 'Int' and 'String' do not share a type, they are both convertible to 'Any', the argument to 'print'. So because of the call to 'print', 'T' becomes 'Any', and the expression becomes, essentially
print((t1 as Any?) ?? ("asdf" as Any))
(Actually, the signature of 'print' is a little more complicated than that, but that's the gist of what's going on.)
Jordan
> On Apr 18, 2016, at 2:51, tuuranton--- via swift-users <swift-users at swift.org> wrote:
>
> Why does this compile?
>
> let t1: Int? = 2
> print(t1 ?? "asdf")
>
> The type of ?? is this:
>
> @warn_unused_result
> public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T
>
> The type syas that T must be the same type throughout. But above I could successfully use Int? and then String. Why?
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160418/3901cc62/attachment.html>
More information about the swift-users
mailing list