在Swift 2中更改数组中字典的值

时间:2015-12-21 22:40:23

标签: swift nsarray swift2 nsdictionary

我正在尝试更改数组中字典的值。我在PlayGround中制作了一个小型原型:

var arr = [NSDictionary]()
arr.append(["name":"blue","view":"<object id=\"6787\">","visible":"true","locked":"false"])
arr.append(["name":"yellow","view":"<object id=\"345\">","visible":"true","locked":"false"])
arr.append(["name":"green","view":"<object id=\"123\">","visible":"false","locked":"true"])

//test remove
arr.removeAtIndex(2)

arr.count

//test edit
let nameChange = arr[1]
nameChange.setValue("black", forKey: "name")

arr[1]

但是发生了错误,我无法解决: enter image description here

有些人可以帮助我吗?

2 个答案:

答案 0 :(得分:5)

因为您将字典创建为NSDictionary - 所以这些值在设置后无法更改。但您仍然希望使用setValue()更改它们,这就是您遇到错误的原因。修复很简单,将其更改为NSMutableDictionary。的 BUT 即可。当你有Swift API时,你不应该使用Objective-C API。这就是为什么你应该使用Swift的Dictionary。怎么样? e.g。

var arr = [[String:String]]()
arr.append(["name":"blue","view":"<object id=\"6787\">","visible":"true","locked":"false"])
arr.append(["name":"yellow","view":"<object id=\"345\">","visible":"true","locked":"false"])
arr.append(["name":"green","view":"<object id=\"123\">","visible":"false","locked":"true"])

//test remove
arr.removeAtIndex(2)

arr.count

//test edit
var nameChange = arr[1]
nameChange["name"] = "black"

答案 1 :(得分:-1)

终于得到了一些代码,

let DuplicateArray: NSArray = array
let DuplicateMutableArray: NSMutableArray = []
DuplicateMutableArray.addObjectsFromArray(DuplicateArray as [AnyObject])
var dic = (DuplicateMutableArray[0] as! [NSObject : AnyObject])
dic["is_married"] = "false"
DuplicateMutableArray[self.SelectedIndexPath] = dic
array = []
array = (DuplicateMutableArray.copy() as? NSArray)!

//输出将像

array =  [
  {
    "name": "Kavin",
    "Age": 25,
    "is_married": "false"
  },
  {
    "name": "Kumar",
    "Age": 25,
    "is_married": "false"
  }