Gar*_*ett 2 arrays struct ios swift
我有一系列struct符合的MyProtocol。我需要这些结构类型的数组(因为它们声明了一个静态方法,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
Run Code Online (Sandbox Code Playgroud)
这个怎么样?:
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
Run Code Online (Sandbox Code Playgroud)