Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode/Decode enum for Swift (Xcode 6.1) [duplicate]

Tags:

enums

ios

swift

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?

like image 343
CaptainCOOLGUY Avatar asked Oct 18 '14 08:10

CaptainCOOLGUY


1 Answers

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"))
}
like image 81
rintaro Avatar answered Oct 20 '22 05:10

rintaro