Skip to content

Instantly share code, notes, and snippets.

@jarakys
Created December 12, 2022 14:42
Show Gist options
  • Select an option

  • Save jarakys/45ec76fa5d26101e6dcbf74875c8b27d to your computer and use it in GitHub Desktop.

Select an option

Save jarakys/45ec76fa5d26101e6dcbf74875c8b27d to your computer and use it in GitHub Desktop.
struct UserDefaultsStorage: Storage {
func remove<T>(key: LocalKey, value: T) {
}
private let storage = UserDefaults.standard
func set<T>(key: LocalKey, value: T) where T : Codable {
storage.set(try? JSONEncoder().encode(value), forKey: key.rawValue)
storage.synchronize()
}
func add<T>(key: LocalKey, value: T) where T : Codable {
guard var array: [T] = get(key: key) else {
set(key: key, value: [value])
return
}
array.append(value)
set(key: key, value: array)
}
func remove<T>(key: LocalKey, value: T) where T : Codable, T : Equatable {
guard var array: [T] = get(key: key) else {
return
}
array.removeAll(where: {value == $0} )
set(key: key, value: array)
}
func get<T>(key: LocalKey) -> T? where T : Decodable {
guard let data = storage.object(forKey: key.rawValue) as? Data else { return nil }
return try? JSONDecoder().decode(T.self, from: data)
}
func get<T>(key: LocalKey, defaultValue: T) -> T where T : Decodable {
guard let data = storage.object(forKey: key.rawValue) as? Data else { return defaultValue }
return (try? JSONDecoder().decode(T.self, from: data)) ?? defaultValue
}
func clear(key: LocalKey) {
storage.setValue(nil, forKey: key.rawValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment