I created the following class to ease UserDefaults get/set within my Swift project.
class MyDefaults {
enum Key: String, CaseIterable {
case email // String
case password // String
}
static private let defaults = UserDefaults.standard
static func set(_ value: Any?, key: Key) { // to set value using enum key
defaults.setValue(value, forKey: key.rawValue)
}
static func get(key: Key) -> Any? { // get value using enum key
return defaults.value(forKey: key.rawValue)
}
static func hasValue(key: Key) -> Bool { // check value if exist or nil
return defaults.value(forKey: key.rawValue) != nil
}
static func removeAll() { // remove all stored values
for key in Key.allCases {
defaults.removeObject(forKey: key.rawValue)
}
}
}
The aim is to use the class as follows:
let email = MyDefaults.get(key: .email)
MyDefaults.set(email, key: .email)
Note: I used static
in class method in order to use it as type i.s.o. class instance.
I'm not sure about the static
for the property 'defaults'. Xcode complaints if I omit it.
Is above code correct and/or is there something I missed?