Floyd Resler Floyd Resler - 1 year ago 101
iOS Question

iOS Swift Updating Dictionary In An Array

I have an array of dictionaries inside a dictionary. I initialize it like this:

var fillups:[NSMutableDictionary] = []

Then I load it like this:

fillups = userDefaults.object(forKey: car) as! NSArray as! [NSMutableDictionary]

Then when I try to update a dictionary element in the array I get the "mutating method sent to immutable object" error. Here's my code to update the record:

let dict=fillups[row]
dict.setValue(odometerField.text, forKey: "odometer")
dict.setValue(gallonsField.text, forKey: "gallons")

The error occurs in my first setValue line.

dan dan
Answer Source

Objects that you retrieve from NSUserDefaults are immutable even if they were mutable when they were inserted. You need to take the immutable objects you get from defaults and create mutable versions of them. You also shouldn't force unwrap everywhere if you don't want your app to crash.

if let array = userDefaults.object(forKey: car) as? [NSDictionary] {
    fillups = array.map { ($0.mutableCopy() as! NSMutableDictionary) }

You also don't need the fillips[row] = dict line since NSMutableDictionary is a reference type and editing the reference you pull out of the array is already editing the one inside the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download