如何更新swift字典值

时间:2016-06-18 20:55:53

标签: arrays swift swift-dictionary

我从php重写了这段代码。我发现很难让它迅速发挥作用。

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

2 个答案:

答案 0 :(得分:6)

据推测,您希望在分配arrayOfData时更新data["count"] = 8内的值。如果您切换到使用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
}

答案 1 :(得分:3)

假设你的数组必须是'[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
}