Is there a more elegant way to increment a counter stored in user defaults?
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(defaults.integerForKey("counter")+1, forKey: "counter")
No but if you do this a lot it might make a nice extension, something like this.
extension NSUserDefaults {
class func incrementIntegerForKey(key:String) {
let defaults = standardUserDefaults()
let int = defaults.integerForKey(key)
defaults.setInteger(int+1, forKey:key)
}
}
Usage like this
NSUserDefaults.incrementIntegerForKey("counter")
This is the same as the solution offered by Wezly, but it reuses my global defaults
object and and allows me to modify the value.
extension NSUserDefaults {
func incrementIntegerForKey(key:String, by: Int) {
let int = integerForKey(key)
setInteger(int + by, forKey:key)
}
}
Used like so (assuming you've defined defaults elsewhere):
defaults.incrementIntegerForKey("counter", by: -3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With