I am trying to save data from a Struct into UserDefaults and then read from it. So far the code seem to work ok with Encoding the data, but when I am trying to decode, it does not return any data.
Please find my codes listed below:
My Struct:
struct GameSetting: Codable {
var gameSetupText: String?
var gamePicker: Int
var groupSetupButton: Int }
To write to Userdefaults:
public let defaults = UserDefaults.standard
public let encoder = JSONEncoder()
func encodeDefault(dataModel: [GameSetting]) {
if let encodedModel = try? encoder.encode(dataModel) {
defaults.set(encodedModel, forKey: "encodedModel")
}
}
and to Decode I used the following code:
public let decoder = JSONDecoder()
if let savedModel = defaults.value(forKey: "encodedModel") as? Data {
if let decodedData = try? decoder.decode(GameSetting.self, from: savedModel) {
print("Decoded data: \(decodedData)")
}
}
I have searched around in SO and other resources, but dont seem to find the answer i need. Hope you could help me and provide some advise on what to do next?
Thank you for your recommendation to use a Do/Catch or Try/Catch as it revealed that there was a type error in my code. I encoded an Array: [GameSetting], but decoded a dictionary GameSetting. The corrected code is here:
public let decoder = JSONDecoder()
if let savedModel = defaults.value(forKey: "encodedModel") as? Data {
if let decodedData = try? decoder.decode([GameSetting].self, from: savedModel) {
print("Decoded data: \(decodedData)")
}
}