I am new to Swift and am developing an application that has a few dozen values that it needs to store in UserDefaults - login credentials, tuning parameters, etc - that often need to be accessed during the app's execution. With how extensible the language seems to be I am wondering if there is a clean way to dynamically manage the large number of variables that this would entail. This is the closest I could come up with.
First, set up an enum for all of the keys that will be used:
extension UserDefaults {
enum Keys : String{
case userName, password, serverIP, syncInterval, ......
}Next, set up the defaults:
let defaults:[String:Any] =
[UserDefaults.Keys.userName.rawValue : "",
UserDefaults.Keys.password.rawValue : "",
UserDefaults.Keys.serverIP.rawValue : "0.0.0.0",
UserDefaults.Keys.syncInterval.rawValue : 60,
......]
UserDefaults.standard.register(defaults:defaults)Next, define a computed property for each value:
class var serverIP: String {
get {
return UserDefaults.standard.string(forKey: UserDefaults.Keys.serverIP.rawValue)!
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.Keys.serverIP.rawValue)
}
}
class var syncInterval: Int {
get {
return UserDefaults.standard.integer(forKey: UserDefaults.Keys.syncInterval.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: UserDefaults.Keys.syncInterval.rawValue)
}
}
......And then just use UserDefaults.serverIP in the code whenever I need to make a web request. I like how this reads but I am concerned about whether it is too inefficient to load from UserDefaults every time?
Also, it annoys me how independent and manual these three segments of code are; is there a way to dynamically build a list of enums and/or computed properties based on a dictionary of default values? Or some other approach to build a way of accessing these properties dynamically?
Maybe I'm just overthinking things but this seems like a not uncommon use case, so I'm hoping there are some elegant solutions out there. Thanks!