[英]Swift array of struct types conforming to protocol
我有一系列符合MyProtocol
struct
。 我需要这些结构类型的数组(因为它们具有在MyProtocol
中声明的静态方法,我需要能够访问该方法)。 我已经尝试过各种方法,但无法使Xcode像这样。
另外,在将此标记为“欺骗”之前,我尝试过此方法 ,但得到的只是:
//Foo and Bar are structs conforming to MyProtocol
let MyStructArray: Array<MyProtocol.self> = [Foo.self, Bar.self]
//Protocol 'MyProtocol' can only be used as a generic constant because it has Self or associated type requirements
这个怎么样?:
protocol MyProtocol {
static func hello()
}
struct Foo: MyProtocol {
static func hello() {
println("I am a Foo")
}
var a: Int
}
struct Bar: MyProtocol {
static func hello() {
println("I am a Bar")
}
var b: Double
}
struct Baz: MyProtocol {
static func hello() {
println("I am a Baz")
}
var b: Double
}
let mystructarray: Array<MyProtocol.Type> = [Foo.self, Bar.self, Baz.self]
(mystructarray[0] as? Foo.Type)?.hello() // prints "I am a Foo"
for v in mystructarray {
switch(v) {
case let a as Foo.Type:
a.hello()
case let a as Bar.Type:
a.hello()
default:
println("I am something else")
}
}
// The above prints:
I am a Foo
I am a Bar
I am something else
我发现了问题。 我的协议是从RawOptionSetType
继承的。 不知道为什么会引起问题,但是注释掉继承使其起作用。 奇怪的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.