如何以通用方式调用协议上的静态函数? [英] How can I call a static function on a protocol in a generic way?
问题描述
在协议上声明静态函数有什么意义吗?使用协议的客户端无论如何都必须在符合协议的类型上调用该函数,对吗?这打破了不必知道符合 IMO 协议的类型的想法.有没有一种方法可以在我不必知道符合我的协议的实际类型的情况下调用协议上的静态函数?
Is there a point to declaring a static function on a protocol? The client using the protocol has to call the function on a type conforming to the protocol anyway right? That breaks the idea of not having to know the type conforming to the protocol IMO. Is there a way to call the static function on the protocol in a way where I don't have to know the actual type conforming to my protocol?
推荐答案
好问题.这是我的拙见:
Nice question. Here is my humble point of view:
与在协议中声明实例方法几乎相同.
Pretty much the same as having instance methods declared in a protocol.
是的,就像实例函数一样.
Yes, exactly like instance functions.
没有.看下面的代码:
protocol Feline {
var name: String { get }
static func createRandomFeline() -> Feline
init()
}
extension Feline {
static func createRandomFeline() -> Feline {
return arc4random_uniform(2) > 0 ? Tiger() : Leopard()
}
}
class Tiger: Feline {
let name = "Tiger"
required init() {}
}
class Leopard: Feline {
let name = "Leopard"
required init() {}
}
let feline: Feline = arc4random_uniform(2) > 0 ? Tiger() : Leopard()
let anotherFeline = feline.dynamicType.createRandomFeline()
我不知道变量 feline
中的真实类型.我只知道它确实符合Feline
.但是我调用的是静态协议方法.
I don't know the real type inside the variable feline
. I just know that it does conform to Feline
. However I am invoking a static protocol method.
我明白了,您想调用协议中声明的静态方法/函数,而不创建符合协议的值.
I see, you would like to call a static method/function declared in a protocol without creating a value that conforms to the protocol.
像这样:
Feline.createRandomFeline() // DANGER: compiler is not happy now
老实说,我不知道这是不可能的原因.
Honestly I don't know the reason why this is not possible.
这篇关于如何以通用方式调用协议上的静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!