Skip to content

Instantly share code, notes, and snippets.

@EkkoG
Created October 12, 2021 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EkkoG/e5a5e8f1d0656fbd8ea8b550d5a58581 to your computer and use it in GitHub Desktop.
Save EkkoG/e5a5e8f1d0656fbd8ea8b550d5a58581 to your computer and use it in GitHub Desktop.
extension KeyedEncodingContainer {
public mutating func encode<T>(_ value: T, forKey key: KeyedEncodingContainer<K>.Key) throws where T : NSCoding {
let data = try NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false)
try encode(data, forKey: key)
}
}
extension KeyedDecodingContainer {
public func decode<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T? where T : NSCoding {
let data = try decode(Data.self, forKey: key)
return try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? T ?? nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment