Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store enum into Mutable Array in swift

Tags:

ios

ios9

swift

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);

like image 422
Gobi M Avatar asked Dec 03 '25 22:12

Gobi M


1 Answers

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
like image 131
Cristik Avatar answered Dec 05 '25 12:12

Cristik



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!