gpt4 book ai didi

ios - 符合协议(protocol)的 Swift 结构类型数组

转载 作者:可可西里 更新时间:2023-11-01 00:37:37 43 4
gpt4 key购买 nike

我有一系列符合 MyProtocolstruct。我需要这些结构的 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

最佳答案

这个怎么样?

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)的 Swift 结构类型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281468/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com