如何将字段添加到 NSMutableDictionary Swift [重复]
Posted
技术标签:
【中文标题】如何将字段添加到 NSMutableDictionary Swift [重复]【英文标题】:How to add field to NSMutableDictionary Swift [duplicate] 【发布时间】:2017-03-21 06:00:43 【问题描述】:这是我尝试过的
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:]: mutating method sent to immutable object”
这是我的字典的布局方式:
[
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;
]
我不确定我做错了什么。我的 bar 字典是可变的,为什么我不断将 mutating 方法发送到不可变对象错误?
【问题讨论】:
***.com/questions/32739508/… 为您的错误代码。 【参考方案1】:在 swift 中使用Dictionary
而不是NSDictionary
。此外,您需要在声明Dictionary
变量时提供type
。
试试这个:
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"
异常。
【讨论】:
你就是男人!!!开箱即用!【参考方案2】:类视图控制器: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
【讨论】:
以上是关于如何将字段添加到 NSMutableDictionary Swift [重复]的主要内容,如果未能解决你的问题,请参考以下文章