Skip to content

Instantly share code, notes, and snippets.

@SergLam
Created May 24, 2023 08:51
Show Gist options
  • Save SergLam/7d92b5dca065a5609b580f3301e1b0cf to your computer and use it in GitHub Desktop.
Save SergLam/7d92b5dca065a5609b580f3301e1b0cf to your computer and use it in GitHub Desktop.
UserDefaults+Codable - handy extension for Codable models storing in UserDefaults
import Foundation
private let jsonDecoder: JSONDecoder = {
let decoder = JSONDecoder()
if #available(iOS 10.0, *) {
decoder.dateDecodingStrategy = JSONDecoder.DateDecodingStrategy.iso8601
}
return decoder
}()
private let jsonEncoder: JSONEncoder = {
let encoder = JSONEncoder()
if #available(iOS 10.0, *) {
encoder.dateEncodingStrategy = JSONEncoder.DateEncodingStrategy.iso8601
}
return encoder
}()
private
struct Container<ObjectType: Codable>: Codable {
let object: ObjectType
}
extension UserDefaults {
func set<ObjectType: Codable>( object: ObjectType?, forKey defaultName: String) {
guard let object = object else {
self.removeObject(forKey: defaultName)
return
}
let container = Container(object: object)
do {
let data = try jsonEncoder.encode(container)
self.set(data, forKey: defaultName)
} catch {
assertionFailure(error.localizedDescription)
// ErrorLoggerService.logWithTrace(error: error)
}
}
func get<ObjectType: Codable>(forKey defaultName: String, type: ObjectType.Type) -> ObjectType? {
guard let data = self.data(forKey: defaultName) else {
return nil
}
do {
let container = try jsonDecoder.decode(Container<ObjectType>.self, from: data)
return container.object
} catch {
assertionFailure(error.localizedDescription)
// ErrorLoggerService.logWithTrace(error: error)
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment