Home > Back-end >  Changing value in Dictionary in a Array in UserDefaults
Changing value in Dictionary in a Array in UserDefaults

Time:11-01

I have a problem changing the value of a Dictionary in a Array

var array = (defaults.array(forKey: "Transactions")! as! [Dictionary<String, Any>])
        
(array.reversed()[index]["Title"] as! String) = titleTextField.text! // Cannot assign to immutable expression of type 'String'

Cannot assign to immutable expression of type 'String'

This is the error I get back

Is there a solution to this problem?

CodePudding user response:

As Joakim points out, array.reversed() returns an immutable array.

Try this:

guard 
  var array = (defaults.array(forKey: "Transactions")! as? [Dictionary<String, Any>]),
  let newText = titletextfield.text,
array[array.count-index]["Title"] = newText

(And then re-save your array to UserDefaults)

CodePudding user response:

One more step will work

if var array = UserDefaults.standard.array(forKey: "Transactions") as? [Dictionary<String, Any>], let valueText = titleTextField.text {
    array.reverse()
    array[index]["Title"] = valueText
 }
  • Related