Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift array holding any enum String type

How would I declare an array in Swift which can hold values of any enum String type?

Here's what I want to do:

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

The two enum types are loosely related but definitely distinct and I need to keep the values separated in this instance, so lumping them all together in one enum and declaring the array of type MyAllIncludingEnumType is not desirable.

Or should I just declare an array of Strings and add the rawValues directly?

I could declare the array as [AnyObject] but then I'd have to type check each element before attempting to access the .rawValue, which isn't great either.

Currently I'm only able to use Swift 1.2 on this project, as it's for an app which is already in the App Store and I need to be able to ship updates before Xcode 7 goes GM.

Or is there a cleaner but completely alternate solution to what I want to do?

like image 496
Andrew Ebling Avatar asked Aug 11 '26 03:08

Andrew Ebling


1 Answers

An alternative to Kametrixom's answer is to make both enums conform to a common protocol. Both automatically conform to RawRepresentable, because of the raw value of String:

protocol RawRepresentable {
    typealias RawValue
    var rawValue: RawValue { get }
    ...
}

However, you cannot use this as the type stored in the array since RawRepresentable is a generic protocol. Instead you could do:

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
like image 114
ABakerSmith Avatar answered Aug 15 '26 01:08

ABakerSmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!