Making NSUserDefault of type Integer in Swift

Swift 3:

You could just use the set(Int, forKey: String) method Swift provides:

//Set
UserDefaults.standard.set(yourInt, forKey: "intKey")
//Get
UserDefaults.standard.integer(forKey: "intKey")

Swift 2:

You could just use the setIntegerForKey-method Swift provides:

let defaults = NSUserDefaults.standardUserDefaults()

//Set
defaults.setInteger(yourInt, forKey: "intKey")
//Get
defaults.integerForKey("intKey")

Please note that in the very latest version of Swift 3 you don't have to indicate data type. Just write:

UserDefaults.standard.set(DataType, forKey:"DATAKEY")

Example:

UserDefaults.standard.set(5, forKey:"MY_INTEGER")
UserDefaults.standard.set("", forKey:"MY_STRING")
UserDefaults.standard.set(true, forKey:"MY_BOOLEAN")

See this Apple documentation for more information and on how to retrieve the stored data type.

Tags:

Ios

Swift