相关疑难解决方法(0)

如何调用更具体的重载方法

这是一个示例游乐场:

protocol P {
    associatedtype T
    func getValue() -> T
}

class Foo: P {
    func getValue() -> String {
        return "hello"
    }
}

class Bar {
    func test<T: P>(_ o: T) {
        print("Generic", o.getValue())
    }

    func test(_ o: Any) {
        print("Any")
    }
}

let foo = Foo()
let bar = Bar()
bar.test(foo)
Run Code Online (Sandbox Code Playgroud)

这输出:Any.

如果我删除Any版本test,则调用泛型方法.类Foo符合协议P,为什么Swift不选择泛型方法,因为它更具体?有没有办法调用通用的?

generics overloading swift

5
推荐指数
1
解决办法
462
查看次数

标签 统计

generics ×1

overloading ×1

swift ×1