[swift-users] Optionals and method overloading with Any
jgroff at apple.com
Thu Jan 7 11:32:08 CST 2016
> On Jan 7, 2016, at 9:12 AM, Don Wills via swift-users <swift-users at swift.org> wrote:
> OK, I'll raise a bug. But it brings up a bigger question - what are the rules for overloading method resolution in the context of optionals? Is that a separate bug, or just a documentation issue?
When you use an implicitly-unwrapped optional type like String! here, it can implicitly convert to String, or it can convert to a supertype such as Any. When more than one conversion is possible, the type checker currently always scores the String! to String conversion lower than other conversions, since it would rather perform a safe upcast than a potentially-trapping String! to String conversion, leading to the behavior you're seeing now.
We plan to rework how T! types work soon in order to make their behavior more predictable. I think the plan is to make expressions involving T! always immediately convert to T unless they're in an immediately Optional context, which would give you the behavior you expect in this case. cc'ing Joe Pamer, who's working on the design here.
More information about the swift-users