Save Codable to UserDefaults

extension UserDefaults { func object<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? { guard let data = self.value(forKey: key) as? Data else { return nil } return try? decoder.decode(type.self, from: data) } func set<T: Codable>(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) { let data = try? encoder.encode(object) self.set(data, forKey: key) } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.