Swift 符合协议的结构类型数组
Swift array of struct types conforming to protocol
我有一系列符合MyProtocol
的几个struct
。我需要这些结构的数组 types(因为它们在 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
。不知道为什么会导致问题,但评论说继承使它起作用。奇怪。
我有一系列符合MyProtocol
的几个struct
。我需要这些结构的数组 types(因为它们在 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
。不知道为什么会导致问题,但评论说继承使它起作用。奇怪。