I'm sick of repeating countless coolFeatureEnabled
string literals while working with UserDefaults
. If there a good way to get rid of them with Swift 3?
var coolFeatureEnabled: Bool {
get { return UserDefaults.standard.bool(forKey: "coolFeatureEnabled") }
set { UserDefaults.standard.set(newValue, forKey: "coolFeatureEnabled") }
}
Here is how to avoid string literals with #function
in Swift 3
// a little bit of setup
private func getBool(key: String = #function) -> Bool {
return UserDefaults.standard.bool(forKey: key)
}
private func setBool(_ newValue: Bool, key: String = #function) {
UserDefaults.standard.set(newValue, forKey: key)
}
// and here is the fun part
var coolFeatureEnabled: Bool {
get { return getBool() }
set { setBool(newValue) }
}
var anotherFeatureEnabled: Bool {
get { return getBool() }
set { setBool(newValue) }
}
...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments