Reputation: 21
I've been trying to add values to array from UserDefaults.standard.
my step:
if it has a value in UserDefaults, adding the value to the array.
@IBAction func addfavorite(_ sender: Any) {
UserDefaults.standard.set(myIndex, forKey:arr[myIndex])
}
for myIndex in 0..<100 {
if UserDefaults.standard.bool(forKey:arr[myIndex]) != nil {
favoriteArr.append(myIndex)
}
}
Comparing non-optional value of type 'Bool' to 'nil' always returns true
Upvotes: 1
Views: 73
Reputation: 236568
The issue there is that bool(forKey:)
method will always return false
if there is no value for a key because it returns a non optional Bool
. An alternative to check against nil is to use UserDefaults
method object(forKey:)
which returns Any?
If your intent is just to persist an array of integers you can extend UserDefaults and create a computed property with a getter and a setter to make your data persist automatically:
extension UserDefaults {
var favorites: [Int] {
get { array(forKey: "favorites") as? [Int] ?? [] }
set { set(newValue, forKey: "favorites") }
}
}
UserDefaults.standard.favorites = []
UserDefaults.standard.favorites.append(2)
UserDefaults.standard.favorites.append(7)
UserDefaults.standard.favorites // [2,7]
Upvotes: 1