我想弄清楚是否可以像在 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
)的元类型参数,其中 T
是 RawRepresentable
而且,在你的情况下,它的 RawValue
是 Int
。
这将允许您传入 Foo
和 Bar
的元类型,拼写为 Foo.self
和 Bar.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/