符合协议的Swift数组结构类型

时间:2015-05-16 22:39:33

标签: ios arrays swift struct

我有一系列struct符合MyProtocol。我需要这些结构'类型的数组(因为它们在MyProtocol中声明了我需要能够访问的静态方法)。我尝试了各种各样的东西,但我不能让Xcode像它一样。

此外,在此之前被标记为欺骗 - 我尝试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

2 个答案:

答案 0 :(得分:5)

这个怎么样?:

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

答案 1 :(得分:0)

我发现了问题。我的协议继承自RawOptionSetType。不确定为什么会引起一个问题,但评论继承是否有效。怪异。