Skip to content

Instantly share code, notes, and snippets.

@NinoScript
Last active December 2, 2019 10:47
Show Gist options
  • Save NinoScript/47819cf6fe36d6845aee32d19b423e9b to your computer and use it in GitHub Desktop.
Save NinoScript/47819cf6fe36d6845aee32d19b423e9b to your computer and use it in GitHub Desktop.
NSCoding a Swift Enum
//: Playground - noun: a place where people can play
import Cocoa
enum Enum {
case SimpleCase
case AssociatedValue(String)
case AnotherAssociated(Int)
}
extension Enum {
enum Base: String {
case SimpleCase
case AssociatedValue
case AnotherAssociated
}
var base: Base {
switch self {
case .SimpleCase: return .SimpleCase
case .AssociatedValue: return .AssociatedValue
case .AnotherAssociated: return .AnotherAssociated
}
}
}
class Class: NSObject, NSCoding {
var e: Enum
// Memberwise initializer
init(e: Enum) {
self.e = e
}
// MARK: NSCoding
required convenience init?(coder decoder: NSCoder) {
guard
let rawCase = decoder.decodeObjectForKey("case") as? String,
let base = Enum.Base(rawValue: rawCase)
else { return nil }
let e: Enum
switch base {
case .SimpleCase:
e = .SimpleCase
case .AssociatedValue:
guard
let value = decoder.decodeObjectForKey("value") as? String
else { return nil }
e = .AssociatedValue(value)
case .AnotherAssociated:
let value = decoder.decodeIntegerForKey("value")
e = .AnotherAssociated(value)
}
self.init(e: e)
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(e.base.rawValue, forKey: "case")
switch e {
case .SimpleCase: break
case .AssociatedValue(let value): coder.encodeObject(value, forKey: "value")
case .AnotherAssociated(let value): coder.encodeInt(Int32(value), forKey: "value")
}
}
}
let e = Class(e: .AnotherAssociated(154))
let arcvd = NSKeyedArchiver.archivedDataWithRootObject(e)
let unarc = NSKeyedUnarchiver.unarchiveObjectWithData(arcvd)
let c = unarc as? Class
c?.e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment