我想要这样声明:
var types:Array<T.Type where T:Cacheable> = []
存储T.self。但是语法是错误的。正确的方法是什么?谢谢。
为了更加清楚,这是我想要做的简短描述:
protocol Cacheable {
class func cacheKey() -> String
}
class User:Cacheable {
class func cacheKey() -> String {
return "user"
}
}
class Post:Cacheable {
class func cacheKey() -> String {
return "post"
}
}
func initTables(type: Cacheable.Type) {
println(type.cacheKey()) // errors if use @Matt solution
}
func startup() {
for type:Cacheable.Type in [User.self, Post.self] {
initTables(type)
}
}
我尝试了这个,它似乎起作用:
protocol Cacheable {}
struct S1 : Cacheable {}
struct S2 : Cacheable {}
var types : Array<Cacheable.Type> = []
// and this shows that we can actually store types in the array
types.append(S1)
types.append(S2)
而且,如果您尝试说错types.append(String)
了什么,例如编译器阻止了您,并抱怨String不符合Cacheable,这正是我们希望它说的...!
编辑好的,所以您已经移动了问题的门柱。这是一个有趣的新问题,但这是一个完全不同的问题。这里的问题是协议是“存在的元类型”,而不是“元类型”。您不能通过协议多态地访问类函数。您必须改用超类。这有效:
class Super {
class func cacheKey() -> String {
return "super"
}
}
class User:Super {
override class func cacheKey() -> String {
return "user"
}
}
class Post:Super {
override class func cacheKey() -> String {
return "post"
}
}
func test() {
for type : Super.Type in [User.self, Post.self] {
println(type.cacheKey())
}
}
因此,如果您没有Post和User的其他超类,请给他们一个任意的超类Super。如果确实有Post和User的超类,则cacheKey()
在扩展名中为该类提供类func 。无论哪种方式,您现在都拥有一个多态类func cacheKey
。
但是,您真正的问题似乎是第三件事,即如何获得类的唯一标识符。可能有比使用此类的类函数更好的方法!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句