Henrik Henrik - 3 years ago 259
Swift Question

Increment integer in NSUserDefaults

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")

Answer Source

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download