我只是在试图弄清楚 Swift 泛型时想到这个。我想出了以下测试代码,我想在其中调用 f()
。在这种情况下,我不知道如何告诉编译器 T
是 Classy
。
protocol Prot {
func doSomething()
static func instance() -> Prot
}
class Classy: Prot {
func doSomething() {
print("here")
}
static func instance() -> Prot {
return Classy()
}
}
func f<T: Prot>() {
T.instance().doSomething()
}
f() // error
f<Classy>() // error
最佳答案
试试这个:
f<T: Prot>(t: T.Type) {
t.instance().doSomething()
}
f(Classy.self)
我现在不在可以测试它的地方,但我过去使用过这种技术并且它有效。
关于swift - 我怎样才能调用这个通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629882/