如何向NSMutableDictionary Swift添加字段

时间:2017-03-21 06:00:43

标签: ios swift dictionary

以下是我尝试的内容

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

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

我的词典中目前没有距离字段,但我想将其添加到字典中并为其设置值。

我一直收到这个错误:

由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:' - [__ NSCFDictionary setObject:forKey:]:发送到不可变对象的变异方法'

以下是我的词典的布局:

[{
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;
}]

我不确定我做错了什么。我的吧字典是可变的,为什么我一直把变异方法发送到不可变对象错误?

2 个答案:

答案 0 :(得分:1)

在swift而不是Dictionary中使用NSDictionary。此外,您需要在声明type变量时提供Dictionary

试试这个:

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

//And this
bars[2]["Distance"] = distanceInMiles
上述代码中的

bars[2]仅在数组bars中包含至少3个元素时才有效。否则它会给"Array index out of bounds"例外。

答案 1 :(得分:0)

类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
}

}