I want to create an array of Ints that I can append to and will be saved to UserDefaults so that next time the user opens the app, the array will be saved. So, I know how to create a UserDefaults array...
var intArray = UserDefaults.standard.array(forKey: "intArray") as! [Int]
and I know how to set the array to an already existing array:
var array = [2, 6, 34, 4, 9]
UserDefaults.standard.set(array, forKey: "intsArray")
But, I need the array to be empty and then the user adds Ints to the array. Thanks for your help!
I would suggest you to create a computed property for this purpose:
var intArray: [Int] {
get {
return UserDefaults.standard.array(forKey: "intArray") as? [Int] ?? []
}
set {
UserDefaults.standard.set(newValue, forKey: "intArray")
}
}
Now whenever you modify your intArray it will update its value in UserDefaults and whenever you call intArray it returns you the value from UserDefaults.
Not sure about what you need.
However this is how you add an empty array to UserDefaults
UserDefaults.standard.set([Int](), forKey: "nums")
And this is how you
.
var nums = UserDefaults.standard.array(forKey: "nums") as! [Int]
nums.append(1)
UserDefaults.standard.set(nums, forKey: "nums")
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