Skip to content

Instantly share code, notes, and snippets.

@beccadax
Last active June 29, 2021 12:52
Show Gist options
  • Save beccadax/849d192f6f224435bc70836317e8391a to your computer and use it in GitHub Desktop.
Save beccadax/849d192f6f224435bc70836317e8391a to your computer and use it in GitHub Desktop.
Encode Codable instances into UserDefaults. Use only with small instances.
//
// UserDefaults+Codable.swift
// Converter UltraLight
//
// Created by Brent Royal-Gordon on 8/31/17.
// Copyright © 2017 Architechies. All rights reserved.
// MIT-licensed, go nuts with it.
//
import Foundation
extension UserDefaults {
func encode<T: Encodable>(_ value: T?, forKey key: String) throws {
let data = try value.map(PropertyListEncoder().encode)
let any = data.map { try! PropertyListSerialization.propertyList(from: $0, options: [], format: nil) }
set(any, forKey: key)
}
func decode<T: Decodable>(_ type: T.Type, forKey key: String) throws -> T? {
let any = object(forKey: key)
let data = any.map { try! PropertyListSerialization.data(fromPropertyList: $0, format: .binary, options: 0) }
return try data.map { try PropertyListDecoder().decode(type, from: $0) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment