gpt4 book ai didi

swift - 可以在 Swift 中将枚举类型名称作为参数传递吗?

转载 作者:IT王子 更新时间:2023-10-29 05:50:10 25 4
gpt4 key购买 nike

我想弄清楚是否可以像在 Swift 中传递 Class 对象一样传递枚举的类型。

我的实际用例比这复杂一点,但为了便于讨论,假设我有两个 Int 枚举:

enum Foo: Int, CustomStringConvertible {
case firstFoo = 0
case anotherFoo = 1
var description: String {
switch self {
case .firstFoo:
return "Hello Foo"
case .anotherFoo:
return "Goodbye Foo"
}
}
}

enum Bar: Int, CustomStringConvertible {
case firstBar = 0
case anotherBar = 1
var description: String {
switch self {
case . firstBar:
return "Hello Bar"
case . anotherBar:
return "Goodbye Bar"
}
}
}

我希望能够编写这样的函数:

func justAnExample(whichEnum: enum) {
let val = whichEnum(rawValue: 0)
print("description: \(String(val))")
}

然后像这样使用它:

justAnExample(Foo)
// prints: "description: Hello Foo"
justAnExample(Bar)
// prints: "description: Hello Bar"

这可能吗?如果是这样,函数声明中whichEnum 的签名是什么?

最佳答案

您可以利用具有原始值的枚举自动符合 RawRepresentable 协议(protocol)这一事实。您可以定义一个通用函数,该函数采用给定类型 T(拼写为 T.Type)的元类型参数,其中 TRawRepresentable而且,在你的情况下,它的 RawValueInt

这将允许您传入 FooBar 的元类型,拼写为 Foo.selfBar.self 分别为:

func justAnExample<T : RawRepresentable>(_ enumType: T.Type) where T.RawValue == Int {

// Note that an explicit use of init is required when creating an instance from a
// metatype. We're also using a guard, as `init?(rawValue:)` is failable.
guard let val = enumType.init(rawValue: 0) else { return }
print("description: \(val)")
}

justAnExample(Foo.self) // prints: "description: Hello Foo"
justAnExample(Bar.self) // prints: "description: Hello Bar"

关于swift - 可以在 Swift 中将枚举类型名称作为参数传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793536/

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