-2

Here is what I've tried

var villages = [NSDictionary]()
var bars = [NSMutableDictionary]()
var allBars = [NSMutableDictionary]()

 (bars[2]).setObject(distanceInMiles, forKey: "Distance" as NSCopying)
  //And this
 bars[2]["Distance"] = distanceInMiles

There is no distance field in my dictionary currently but I'd like to add it to the dictionary and set the value for it.

I keep getting this error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

Here is how my dictionary is laid out:

[{
Latitude = "40.719629";
Longitude = "-74.003939";
Name = "Macao Trading Co";
ObjectID = ayORtpic7H;
PlaceID = ChIJA9S9jIpZwokRZTF0bHWwXYU;
}, {
Latitude = "40.717304";
Longitude = "-74.008571";
Name = "Bar Cyrk";
ObjectID = z7NV2uOmgH;
PlaceID = ChIJaWlspR9awokRvrKEAoUz3eM;
}, {
Latitude = "40.720721";
Longitude = "-74.005489";
Name = "AOA Bar & Grill";
ObjectID = GIst3BLb5X;
PlaceID = ChIJBYvf3IpZwokRJXbThVSI4jU;
}]

I'm not sure what I'm doing wrong. My bars dictionary is mutable so why do I keep getting the mutating method sent to immutable object error?

mocode9
  • 229
  • 3
  • 16
  • http://stackoverflow.com/questions/32739508/nscfdictionary-setobjectforkey-mutating-method-sent-to-immutable-object For your error code. –  Mar 21 '17 at 06:11

2 Answers2

2

Use Dictionary in swift instead of NSDictionary. Also, you need to give the type while declaring the Dictionary variable.

Try this:

var villages = [[String : Any]]()
var bars = [[String : Any]]()
var allBars = [[String : Any]]()

//And this
bars[2]["Distance"] = distanceInMiles

bars[2] in the above code will only work if the array bars has atleast 3 elements in it. Otherwise it will give "Array index out of bounds" exception.

PGDev
  • 23,751
  • 6
  • 34
  • 88
0

class ViewController: UIViewController {

var bars = [NSMutableDictionary]()


override func viewDidLoad() {
    super.viewDidLoad()
    demo()
}

func demo(){

    for _ in stride(from: 0, to: 5, by: 1){
       bars.append(addDictionary(Latitude: "40.719629", Longitude: "-74.003939", Name: "Macao Trading Co", ObjectID: "ayORtpic7H", PlaceID: "ChIJA9S9jIpZwokRZTF0bHWwXYU"))
    }
    print(bars)
}

func addDictionary(Latitude : String? , Longitude : String? , Name : String , ObjectID : String? , PlaceID : String?) -> NSMutableDictionary{

    let tempDict = NSMutableDictionary()
    tempDict["Latitude"] = Latitude
    tempDict["Longitude"] = Longitude
    tempDict["Name"] = Name
    tempDict["ObjectID"] = ObjectID
    tempDict["PlaceID"] = PlaceID

    return tempDict
}

}