[swift-users] Optionals and method overloading with Any
Jeremy Pereira
jeremy.j.pereira at googlemail.com
Thu Jan 7 10:59:05 CST 2016
I think it’s a bug.
This (in which s1 is explicitly unwrapped instead of implicitly unwrapped)
class Test {
private var s1 : String?
func tst() {
let t1 : Test1 = Test1()
t1.mth("abc", s1!)
}
}
compiles just fine and should be equivalent to Don’s original code in which s1 is optional but implicitly unwrapped.
I think you should raise a bug, Don.
> On 7 Jan 2016, at 04:53, Jens Alfke via swift-users <swift-users at swift.org> wrote:
>
>
>> 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.
>
> —Jens
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
More information about the swift-users
mailing list