【发布时间】:2015-08-27 07:38:53
【问题描述】:
如何在 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 类型的数组是不可取的。
或者我应该只声明一个字符串数组并直接添加 rawValues?
我可以将数组声明为 [AnyObject],但在尝试访问 .rawValue 之前,我必须对每个元素进行类型检查,这也不是很好。
目前我只能在这个项目上使用 Swift 1.2,因为它是针对已经在 App Store 中的应用程序,我需要能够在 Xcode 7 通用之前发布更新。
或者对于我想要做的事情,是否有更清洁但完全替代的解决方案?
【问题讨论】: