arrays - 持有任何枚举字符串类型的 Swift 数组

标签 arrays swift enums

我如何在 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/

相关文章:

javascript - 试图定位某人在 Vanilla JS 中点击的属性

ios - 'NSInvalidArgumentException' - [UIViewController tableView :numberOfRowsInSection:] - unrecognized selector sent to instance

swift - 为什么此 Switch 语句需要 'Switch Value' 和 'Compound case' 的括号?

ios - 两个 UIButton 形成一个具有渐变颜色,另一个具有边框和圆角

ios - 如何在 swift 3.0 中拖动和缩放 UIView 内的 UIImageView ?

c++ - 将此枚举传递给 CTOR 有什么问题?

Swift KVO - 观察枚举属性

c# - 如何在 C# 中使用字符串和 double 获取二维数组的用户数据?

c++ - 复制并取消 int 数组

c++ - 为什么我的函数无法使用指针打印多维数组的元素?