mjk
mjk

Reputation: 21

How to add values to array from UserDefaults?

I've been trying to add values to array from UserDefaults.standard.

my step:

  1. adding a value in UserDefaults.
  2. checking the Userdefautls to see if it has a value(from 0 to 100)
  3. 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

Answers (1)

Leo Dabus
Leo Dabus

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

Related Questions