如何更新 swift 字典值

How to update swift dictionary value

我从 php 重写了这段代码。而且我发现很难让它在 swift.

中工作
var arrayOfData = [AnyObject]()

for index in 1...5 {
    var dict = [String: AnyObject]()
    dict["data"] = [1,2,3]
    dict["count"]  = 0

    arrayOfData.append(dict)
}

for d in arrayOfData {

    let data = d as AnyObject

    // I want to update the "count" value
    // data["count"] = 8
    print(data);
    break;
}

假设你的数组必须是 '[AnyObject]' 的形式,那么是这样的:

var arrayOfData = [AnyObject]()

for index in 1...5 {
    var dict = [String: AnyObject]()
    dict["data"] = [1,2,3]
    dict["count"]  = 0

    arrayOfData.append(dict)
}

for d in arrayOfData {

    // check d is a dictionary, else continue to the next 
    guard let data = d as? [String: AnyObject] else { continue }

    data["count"] = 8
}

但最好将您的数组输入为字典数组:

var arrayOfData = [[String: AnyObject]]()

for index in 1...5 {
    var dict = [String: AnyObject]()
    dict["data"] = [1,2,3]
    dict["count"]  = 0

    arrayOfData.append(dict)
}

for d in arrayOfData {
    // swift knows that d is of type [String: AnyObject] already
    d["count"] = 8
}

编辑:

所以问题是,当您在循环中进行修改时,您正在从数组中创建新版本的字典,并且需要将其传回。尝试使用地图:

arrayOfData = arrayOfData.map{ originalDict in
    var newDict = originalDict
    newDict["count"] = 8
    return newDict
}

据推测,您希望在分配 data["count"] = 8 时更新 arrayOfData 内部的值。如果您切换到使用 NSMutableArrayNSMutableDictionary,那么您的代码将按您的意愿工作。这样做的原因是这些类型是引用类型(而不是像 Swift 数组和字典这样的值类型),所以当您使用它们时,您是在引用它们内部的值而不是制作副本。

var arrayOfData = NSMutableArray()

for index in 1...5 {
    var dict = NSMutableDictionary()
    dict["data"] = [1,2,3]
    dict["count"] = 0

    arrayOfData.addObject(dict)
}

for d in arrayOfData {
    let data = d as! NSMutableDictionary
    data["count"] = 8
    print(data)
    break
}