I used to save important App data like login credentials into UserDefaults using the following statement:
UserDefaults.standard.set("sample@email.com&quo
In additon to pawello2222 answer, here. is the reimplementation of the AppStorage that I named it as UserDefaultStorage
:
@propertyWrapper
struct UserDefaultStorage {
private let key: String
private let defaultValue: T
private let userDefaults: UserDefaults
init(key: String, default: T, store: UserDefaults = .standard) {
self.key = key
self.defaultValue = `default`
self.userDefaults = store
}
var wrappedValue: T {
get {
guard let data = userDefaults.data(forKey: key) else {
return defaultValue
}
let value = try? JSONDecoder().decode(T.self, from: data)
return value ?? defaultValue
}
set {
let data = try? JSONEncoder().encode(newValue)
userDefaults.set(data, forKey: key)
}
}
}
This wrapper can store/restore any kind of codable into/from the user defaults. Also, it works in iOS 13 and it doesn't need to import SwiftUI
.
@UserDefaultStorage(key: "myCustomKey", default: 0)
var myValue: Int
Note that it can't be used directly as a State