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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With