我有一系列符合structMyProtocol。我需要这些结构类型的数组(因为它们有一个我需要访问的MyProtocol中声明的静态方法)。我已经尝试过各种方法,但无法使Xcode像这样。

另外,在将此标记为dupe之前,我尝试了this,但是得到的只是:

//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

关于ios - 符合协议(protocol)的结构类型的快速数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30281468/

10-09 02:32