[英]Swift array of struct types conforming to protocol
我有一系列符合MyProtocol
struct
。 我需要這些結構類型的數組(因為它們具有在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
這個怎么樣?:
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
我發現了問題。 我的協議是從RawOptionSetType
繼承的。 不知道為什么會引起問題,但是注釋掉繼承使其起作用。 奇怪的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.