3

How can I store an enum in a mutable array in Swift please?

Below it is discussed for Objective-C and obviously it is working fine. How to store enum values in a NSMutableArray

It is stored for int value using array.addObject(0);

Community
  • 1
  • 1
Gobi M
  • 3,243
  • 5
  • 32
  • 47

2 Answers2

7

You mean like this?

enum MyEnum {
    case Option1,
    Option2,
    Option3,
    Option4
}

var array: [MyEnum] = [.Option1, .Option2]
array.append(.Option3)
let b = MyEnum.Option4
array.append(b)

array[2] // Option3

If you want to store the enum values as integers, you can declare the enum as having the rawValue as an Int and use the rawValue property within the array:

enum MyEnum: Int {
    case Option1,
    Option2,
    Option3,
    Option4
}

var array: [Int] = [MyEnum.Option1.rawValue, MyEnum.Option2.rawValue]
array.append(MyEnum.Option3.rawValue)
let b = MyEnum.Option4
array.append(b.rawValue)

(array as NSArray).objectAtIndex(2) // a NSNumber with value 2
Cristik
  • 30,989
  • 25
  • 91
  • 127
0

Achieved as per @cristik answer

This solved my pblm,

let intervals: NSMutableArray = [Color.red.rawValue, Color.black.rawValue];

Gobi M
  • 3,243
  • 5
  • 32
  • 47