简体   繁体   English

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

[英]Swift array of struct types conforming to protocol

I have a series of several struct s conforming to MyProtocol . 我有一系列符合MyProtocol struct I need an array of these structs' types (because they have a static method declared in MyProtocol that I need to be able to access). 我需要这些结构类型的数组(因为它们具有在MyProtocol中声明的静态方法,我需要能够访问该方法)。 I have tried all kinds of things but I can't make Xcode like it. 我已经尝试过各种方法,但无法使Xcode像这样。

Also, before this is marked as dupe – I tried this , but all I got was: 另外,在将此标记为“欺骗”之前,我尝试过此方法 ,但得到的只是:

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

How about this?: 这个怎么样?:

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

I found the problem. 我发现了问题。 My protocol was inheriting from RawOptionSetType . 我的协议是从RawOptionSetType继承的。 Not sure why that caused an issue, but commenting that inheritance out made it work. 不知道为什么会引起问题,但是注释掉继承使其起作用。 Weird. 奇怪的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM