A.J. A.J. - 16 days ago 5
Swift Question

How can I use variables inside the key of a NSUserDefault?

Is it possible to insert a variable in the key of a

NSUserDefault
?

for example:

NSUserDefault.setInteger(10, forKey: "number /(var)")


I just tried a random syntax, just to make you understand.

Answer

Yes thats possible:

NSUserDefaults.standardUserDefaults().setInteger(10, forKey: "number \(temp)")

here "number \(temp)" is a complete string.

You can try this way to conform:

let temp = 10
NSUserDefaults.standardUserDefaults().setInteger(10, forKey: "number \(temp)")
print(NSUserDefaults.standardUserDefaults().objectForKey("number \(temp)"))

Which will print Optional(10)

Comments