How do I use UserDefaults with SwiftUI?

前端 未结 5 1854
无人共我
无人共我 2020-11-30 00:18
struct ContentView: View {
@State var settingsConfiguration: Settings
    struct Settings {
        var passwordLength: Dou         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 00:43

    If you are persisting a one-off struct such that a property wrapper is overkill, you can encode it as JSON. When decoding, use an empty Data instance for the no-data case.

    final class UserData: ObservableObject {
        @Published var profile: Profile? = try? JSONDecoder().decode(Profile.self, from: UserDefaults.standard.data(forKey: "profile") ?? Data()) {
            didSet { UserDefaults.standard.set(try? JSONEncoder().encode(profile), forKey: "profile") }
        }
    }
    

提交回复
热议问题