Search code examples
swiftoverloadingoverload-resolution

Swift: call overloaded method with ambiguous return type


Suppose I have the following code:

    public class A {}
    public class B : A {}
    public class Foo {
        public func bar() -> A {
            print("secret hidden method")
            return A()
        }

        public func bar() -> B {
            print("easily accessible method")
            return B()
        }
    }

The problem is try to call them leads to ambiguity. You can call bar() -> B with Foo().bar() as B, but all of Foo().bar(), Foo().bar() as A, and let a: A = Foo().bar() yield an Ambiguous use of 'bar()' compiler error.

Bottom line: How do I call bar() -> A? Is there some tricky syntax for it? Is reflection necessary? Is reflection sufficient?


Solution

  • The compiler needs to be able to determine which variation of bar() you want to execute. You can be explicit about the type of func you want to execute, and take advantage of currying to access the correct implementation for a given instance.

    let foo = Foo()
    let a: ()->A = Foo.bar(foo)
    let b: ()->B = Foo.bar(foo)
    a()
    b()
    

    The above code will print:

    secret hidden method
    easily accessible method