I'm wondering what's the best way to store user settings in Swift. With user settings I mean simple (small) data, not some big files. Until now, I used a class with all properties I wanted to be saved.
All of those properties conform to Codable. However, I didn't save the whole class in UserDefaults, instead I saved each property individually. But I don't like that approach. There are several issues with it: The code gets longer because for every variable I have to write didSet{...}. For example:
var percentage: Double = UserDefaults.standard.double(forKey: "percentage") {
didSet {
UserDefaults.standard.set(percentage, forKey: "percentage")
}
}
As you can see, the variable name is written 4 times here. So there is a high chance of misspelling / copy and paste errors.
So why don't I save the whole class then? Well, I noticed that if I add a variable to the class, the decoding of the class doesn't work anymore and all data is lost even if I give the new variable a default value.
There seems to be a way to fix this: decoding manually. For example:
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
//etc...
}
However, decoding manually seems to require me to decode every variable separately. I don't like that as well because there is also a high chance to forget about one variable etc. (so it's the same problem as above).
What I would like to do as well is to give the user the option to export and import settings and to use iCloud for settings synchronization. For the former it would be better to store the whole Settings class (I could export and import the JSON file).
Is there a smart way to do this?
Thanks for helping me out!