extension UserDefaults { /// Sets the codable value of the specified key. func set(_ value: Element, forKey key: String) { let data = try? JSONEncoder().encode(value) UserDefaults.standard.setValue(data, forKey: key) } /// Returns the codable value associated with the specified key. func codable(forKey key: String) -> Element? { guard let data = UserDefaults.standard.data(forKey: key) else { return nil } let element = try? JSONDecoder().decode(Element.self, from: data) return element } }