[swift-users] Optionals and method overloading with Any

Jens Alfke jens at mooseyard.com
Wed Jan 6 22:53:07 CST 2016

> On Jan 6, 2016, at 7:16 PM, Don Wills via swift-users <swift-users at swift.org> wrote:
> Swift method lookup obviously chose the second mth func if it exists, but why?

From the behavior here, it looks like the compiler is first looking for a matching method, then if it can’t find one it unwraps the optional parameter and looks for a match again. So in this case it immediately finds a match (the second mth) and doesn’t try unwrapping the String! parameter.

I have no idea whether that’s correct/intentional behavior, or a bug. I do know that function overloading can create weird situations in any language that supports it (notably C++), so I’m not surprised that there are some edge cases in Swift too.

> I really don't understand optionals.

Well, think of the declaration of s1 as being
	private var s1 : Optional<String>
which is what it actually is under the hood. That makes it pretty clear that the 2nd mth method is the one that will get called. The confusion comes in when you also consider that the compiler will implicitly deref an Optional<String> to String if it’s been declared using “!”, in which case the first mth can be called. Now it’s sort of ambiguous which is preferable.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160106/4b398ed0/attachment.html>

More information about the swift-users mailing list