Created
April 6, 2020 12:57
-
-
Save AndresR173/8c195a9132797f1c7c37ae174063dff2 to your computer and use it in GitHub Desktop.
How to use User Defaults with Property Wrappers
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
import Foundation | |
@propertyWrapper | |
struct UserDefaultsWrapper<Value: Codable> { | |
let key: String | |
let defaultValue: Value | |
let userDefaults = UserDefaults(suiteName: Constants.kGroupIdentifier) | |
var wrappedValue: Value { | |
get { | |
let data = userDefaults?.data(forKey: key) | |
let value = data.flatMap { try? JSONDecoder().decode(Value.self, from: $0) } | |
return value ?? defaultValue | |
} | |
set { | |
let data = try? JSONEncoder().encode(newValue) | |
userDefaults?.set(data, forKey: key) | |
userDefaults?.synchronize() | |
} | |
} | |
} | |
struct Task: Codable, Equatable { | |
let id: UUID | |
var title: String | |
var isDone: Bool | |
} | |
final class DataProvider { | |
@UserDefaultsWrapper(key: Constants.kTaskDefaultKey, defaultValue: defaultTasks) | |
var tasks: [Task] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment