Save dictionary to UserDefaults

后端 未结 2 1045
我寻月下人不归
我寻月下人不归 2021-01-05 05:23

I\'m trying to store a dictionary in UserDefaults and always get app crash when the code runs. Here is the sample code which crashes the app when it is executed. I tried to

2条回答
  •  遥遥无期
    2021-01-05 05:48

    Dictionaries are Codable objects by default, you can use the following extensions to save them to UserDefaults

    extension UserDefaults {
        func object(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
            guard let data = self.value(forKey: key) as? Data else { return nil }
            return try? decoder.decode(type.self, from: data)
        }
    
        func set(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
            let data = try? encoder.encode(object)
            self.set(data, forKey: key)
        }
    }
    

    They can be used like this:

    let test = [1:"me"]
    UserDefaults.standard.set(object: test, forKey: "test")
    
    let testFromDefaults = UserDefaults.standard.object([Int: String].self, with: "test")
    

    This extension and many others are part of SwifterSwift, you might want to use it for your next iOS project :)

提交回复
热议问题