【问题标题】:Swift array of struct types conforming to protocol符合协议的结构类型的 Swift 数组
【发布时间】:2015-05-16 22:39:33
【问题描述】:

我有一系列符合MyProtocol的structs。我需要这些结构的 types 数组(因为它们有一个在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

【问题讨论】:

  • MyProtocol 是你写的协议吗?当你想多态地调用它时,为什么你把它设为静态?

标签: ios arrays swift struct


【解决方案1】:

这个怎么样?

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

【讨论】:

  • 非常适合我。如果你不使用类型注释,编译器就无法猜测数组的类型,我也无法弄清楚它想要什么。非常感谢您启发我。
【解决方案2】:

我发现了问题。我的协议继承自RawOptionSetType。不知道为什么这会导致问题,但评论继承使它起作用。很奇怪。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多