So not sure what I'm doing wrong here with userDefaults and my array. I'm only seeing the last Int
and nothing else added before.
func addItem(completedTask: Int){
var array: [Int] = []
array.append(completedTask)
// Setting userDefaults
let userDefaults = UserDefaults.standard
userDefaults.set(array, forKey: "userDefault-completedItems")
// Read userDefaults
let userDefaultArray = userDefaults.array(forKey: "userDefault-completedItems") as? [Int] ?? [Int]()
print("added items read from userdefaults \(userDefaultArray)")
for item in userDefaultArray {
print(item)
}
}
In the first line of addItem(completedTask:)
, the local variable array
is declared and initialized to an empty array ([]
).
Whether or not UserDefaults has some value, it is initialized as an empty array.
So, when you call userDefaults.set(array, forKey: "userDefault-completedItems")
, array
contains only one item: completedTask
.
I guess you may want to do something like this:
private let kUserDefaultsCompletedItems = "userDefault-completedItems"
func addItem(completedTask: Int){
let userDefaults = UserDefaults.standard
var array: [Int] = userDefaults.array(forKey: kUserDefaultsCompletedItems) as? [Int] ?? []
array.append(completedTask)
// Setting userDefaults
userDefaults.set(array, forKey: kUserDefaultsCompletedItems)
// Read userDefaults
let userDefaultArray = userDefaults.array(forKey: kUserDefaultsCompletedItems) as? [Int] ?? []
print("added items read from userdefaults \(userDefaultArray)")
}