Created
November 16, 2016 16:21
-
-
Save samuelbeek/29b900e72e2616d38cb8519f3b6878c0 to your computer and use it in GitHub Desktop.
Enums with Associated Values that conform to NSCoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspiration: https://gist.github.com/NinoScript/47819cf6fe36d6845aee32d19b423e9b | |
//: Playground - noun: a place where people can play | |
import UIKit | |
enum SavableEnum { | |
case simpleCase | |
case associatedValue(String) | |
case anotherAssociated(Int) | |
} | |
extension SavableEnum { | |
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 SavableEnumWrapper: NSObject, NSCoding { | |
var e: SavableEnum | |
// Memberwise initializer | |
init(e: SavableEnum) { | |
self.e = e | |
} | |
// MARK: NSCoding | |
required convenience init?(coder decoder: NSCoder) { | |
guard | |
let rawCase = decoder.decodeObject(forKey: "case") as? String, | |
let base = SavableEnum.Base(rawValue: rawCase) | |
else { return nil } | |
let e: SavableEnum | |
switch base { | |
case .simpleCase: | |
e = .simpleCase | |
case .associatedValue: | |
guard | |
let value = decoder.decodeObject(forKey: "value") as? String | |
else { return nil } | |
e = .associatedValue(value) | |
case .anotherAssociated: | |
let value = decoder.decodeInteger(forKey: "value") | |
e = .anotherAssociated(value) | |
} | |
self.init(e: e) | |
} | |
func encode(with aCoder: NSCoder) { | |
aCoder.encode(e.base.rawValue, forKey: "case") | |
switch e { | |
case .simpleCase: break | |
case .associatedValue(let value): aCoder.encode(value, forKey: "value") | |
case .anotherAssociated(let value): aCoder.encodeCInt(Int32(value), forKey: "value") | |
} | |
} | |
} | |
let savedEnum = SavableEnumWrapper(e: .anotherAssociated(154)) | |
let arcvd = NSKeyedArchiver.archivedData(withRootObject: savedEnum) | |
let unarc = NSKeyedUnarchiver.unarchiveObject(with: arcvd) | |
let retreivedEnum = unarc as? SavableEnumWrapper | |
retreivedEnum?.e | |
print("sicket test") | |
if let gekkie = retreivedEnum { | |
if case let SavableEnum.anotherAssociated(yolo) = gekkie.e { | |
print("hee", yolo) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment