7

I have

var priority : Priority! = Priority.defaultPriority

func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeInteger(priority.toRaw(), forKey: "priority") //toRaw may not yield the result I am expecting
    }

    required init(coder aDecoder: NSCoder) {
        priority = aDecoder.decodeIntegerForKey("priority") //complaining about conflicting types
    }

with the enum being the following:

enum Priority : Int {
        case defaultPriority = 0
        case lowPriority = 1
        case mediumPriority = 2
        case highPriority = 3
    }

What is the best way to encode/decode this?

CaptainCOOLGUY
  • 1,131
  • 1
  • 14
  • 26
  • Similar question: http://stackoverflow.com/questions/26326645/how-do-i-encode-enum-using-nscoder-in-swift. – Martin R Oct 18 '14 at 08:59

1 Answers1

17

Priority.init(rawValue:) should work.

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeInteger(priority.rawValue, forKey: "priority")
}

required init(coder aDecoder: NSCoder) {
    priority = Priority(rawValue: aDecoder.decodeIntegerForKey("priority"))
}
stephencelis
  • 4,954
  • 2
  • 29
  • 22
rintaro
  • 51,423
  • 14
  • 131
  • 139