我如何在 Swift 中声明一个数组,它可以保存任何 enum
String 类型的值?
这是我想做的:
enum MyEnumType1: String {
case Foo = "foo"
case Bar = "bar"
}
enum MyEnumType2: String {
case Baz = "baz"
}
// ...
// Compiler error: "Type of expression is ambiguous without more context"
var myArray = [ MyEnumType1.Bar, MyEnumType2.Baz ]
// ^ need to declare type here, but not sure of correct syntax
// pass array over to a protocol which will iterate over the array accessing .rawValues
这两个枚举类型松散相关但绝对不同,在这种情况下我需要将值分开,因此将它们全部放在一个枚举中并声明类型为 MyAllIncludingEnumType 的数组是不可取的。
或者我应该只声明一个字符串数组并直接添加原始值吗?
我可以将数组声明为 [AnyObject]
,但是我必须在尝试访问 .rawValue
之前对每个元素进行类型检查,这不是很好要么。
目前我只能在这个项目上使用 Swift 1.2,因为它适用于已经在 App Store 中的应用程序,我需要能够在 Xcode 7 进入 GM 之前发布更新。
或者对于我想做的事情是否有更简洁但完全替代的解决方案?
最佳答案
Kametrixom 的答案的替代方法是使两个枚举都符合通用协议(protocol)。两者都自动符合 RawRepresentable
,因为 String
的原始值:
protocol RawRepresentable {
typealias RawValue
var rawValue: RawValue { get }
...
}
但是,您不能将其用作存储在数组中的类型,因为 RawRepresentable
是一个通用协议(protocol)。相反,你可以这样做:
protocol StringRepresentable {
var rawValue: String { get }
}
enum EnumA: String, StringRepresentable {
case A = "A"
}
enum EnumB: String, StringRepresentable {
case B = "B"
}
let array: [StringRepresentable] = [EnumA.A, EnumB.B]
array[0].rawValue // A
关于arrays - 持有任何枚举字符串类型的 Swift 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32243385/