SwiftUI: What is @AppStorage property wrapper

前端 未结 5 1999
攒了一身酷
攒了一身酷 2020-12-19 03:34

I used to save important App data like login credentials into UserDefaults using the following statement:

UserDefaults.standard.set("sample@email.com&quo         


        
5条回答
  •  自闭症患者
    2020-12-19 03:52

    Re-implementation for iOS 13 and without SwiftUI

    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.

    Usage

    @UserDefaultStorage(key: "myCustomKey", default: 0)
    var myValue: Int
    

    Note that it can't be used directly as a State

提交回复
热议问题