Last active
June 29, 2021 12:52
-
-
Save beccadax/849d192f6f224435bc70836317e8391a to your computer and use it in GitHub Desktop.
Encode Codable instances into UserDefaults. Use only with small instances.
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
// | |
// 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