Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 781
Henrik Avatar asked Feb 13 '16 12:02

Henrik


2 Answers

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")
like image 90
Wez Avatar answered Oct 13 '22 10:10

Wez


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)
like image 37
Henrik Avatar answered Oct 13 '22 11:10

Henrik