简体   繁体   中英

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")
fillups[row]=dict

The error occurs in my first setValue line.

If you want to mutate your dict, you need to declare it with 'var' not with 'let'; 'let' is for constants. Also fix the unwrapping problems pointed out by the comment

let dict=fillups[row]

should be

var dict=fillups[row]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM