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

2
  • Please give us some code regarding the enum and how are you trying to use it in an array, the question is too broad otherwise Commented Jan 21, 2016 at 10:21
  • Why do you think you need to store it as an NSNumber? Commented Jan 21, 2016 at 11:03

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

need to add it a s object type like store as NSNumber. This stores enum values
@GobiM I've updated my answer, please also update your question to reflect that you need to save NSNumber value into the array
Thanks for your time! working, i hv done mistake for using rawValue :D
0

Achieved as per @cristik answer

This solved my pblm,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.