Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert enum to NSNumber in swift

Tags:

enums

swift

Working in Swift, I'd like to convert an enum (of type Int) into NSNumber and back. I can convert from enum to Number but I can't convert back. What's the recommended approach?

enum UpdateMode: Int {
    case Undefined = 0,
         Daily,
         Weekly,
         Monthly
}

var mode = UpdateMode.Weekly
var num: NSNumber = mode.rawValue // this works

// error: 'Int32' is not convertible to 'UpdateMode'
var convertedMode = num.integerValue as UpdateMode 
like image 585
Willam Hill Avatar asked Dec 28 '14 19:12

Willam Hill


1 Answers

There's an initializer for that:

var convertedMode = UpdateMode(rawValue: num.integerValue)

note that it's failable, so convertedMode is an optional - that to account for the integer not mapped to a valid enum case

like image 112
Antonio Avatar answered Sep 20 '22 04:09

Antonio