2014-10-18 15 views
7

Tôi cóMã hóa/Giải mã enum cho Swift (Xcode 6.1)

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 
    } 

với enum là như sau:

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

cách tốt nhất để mã hóa là gì/giải mã này?

+0

Câu hỏi tương tự: http://stackoverflow.com/questions/26326645/how-do-i-encode-enum-using-nscoder-in-swift. –

Trả lời

17

Priority.init(rawValue:) sẽ hoạt động.

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

required init(coder aDecoder: NSCoder) { 
    priority = Priority(rawValue: aDecoder.decodeIntegerForKey("priority")) 
} 
+1

Cảm ơn bạn đã thêm bản cập nhật cho 6.1. – jpittman

+0

Cảm ơn bạn rất hữu ích. – Aaronium112