# NSCoder: Encoding an enum?

**URL:** <https://forums.kodeco.com/t/nscoder-encoding-an-enum/24452>\
**Category:** Swift\
**Created:** [December 24, 2016, 4:57am UTC](https://forums.kodeco.com/t/nscoder-encoding-an-enum/24452 "2016-12-24T04:57:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![robk331](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/robk331/32/57155_2.png) [@robk331](https://forums.kodeco.com/u/robk331)\
**Post date:** [December 24, 2016, 4:57am UTC](https://forums.kodeco.com/t/nscoder-encoding-an-enum/24452/1 "2016-12-24T04:57:51Z")

</div>

Hi All,

I was wondering if there’s some special magic required to encode an enum…

I have a class that has a state which I store in a var called currentState. I’m trying to encode it but when I do I get a “unrecognized selector sent to instance” error. If I remove the state var, the class encodes and decodes fine.

Any suggestions?

Thanks

Rob

enum state {  
case created  
case running  
case paused  
case completed  
}  
…  
var currentState: state  
…  
aCoder.encode(currentState, forKey: “State”) // encoder  
…  
currentState = aDecoder.decodeObject(forKey: “State”) as! state // decoder

---

<div class="post-metadata">

**Author:** ![fusetech](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/fusetech/32/97552_2.png) [@fusetech](https://forums.kodeco.com/u/fusetech)\
**Post date:** [December 25, 2016, 7:10am UTC](https://forums.kodeco.com/t/nscoder-encoding-an-enum/24452/2 "2016-12-25T07:10:38Z")

</div>

You could try having your state enum backed by a primitive, an Int for example. You will probably want to double check my information, but I believe NSCoder has the same restrictions on data types as UserDefaults.

Encoding would be saving the raw value. Decoding would involve getting the raw value, and then casting it as the appropriate state.

Could look something like this:

`
enum state: Int {
case created = 0
case running
case paused
case completed
}
...
aCoder.encode(currentState.rawValue, forKey:"State")
...
guard state = state(rawValue: aDecoder.decodeObject(forKey:"State")) else { 
    //Handle error
}
currentState = state
`

---

<div class="post-metadata">

**Author:** ![robk331](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/robk331/32/57155_2.png) [@robk331](https://forums.kodeco.com/u/robk331)\
**Post date:** [December 27, 2016, 9:00pm UTC](https://forums.kodeco.com/t/nscoder-encoding-an-enum/24452/3 "2016-12-27T21:00:57Z")

</div>

ok, great, I’l give that a shot.

Thanks!

Rob
