skip to Main Content

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?

2

Answers


  1. 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)

    Login or Signup to reply.
  2. 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
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search