James
James

Reputation: 1177

Change value of dictionary within array in Swift 2

I'm trying to change a value of a dictionary that is within an array. I made a small prototype in 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]

But an error occurred, and I can not solve: enter image description here

Some can help me?

Upvotes: 2

Views: 1495

Answers (2)

Kavin Kumar Arumugam
Kavin Kumar Arumugam

Reputation: 1832

Finally Got Some Code,

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)!

//Output Will Be Like

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

]

Upvotes: -1

sunshinejr
sunshinejr

Reputation: 4854

Because you created your dictionary as NSDictionary - the values can't change once they are set. But you still want to change them using setValue() and thats why you have the error. The fix is easy, change it to NSMutableDictionary. BUT. You shouldn't use Objective-C API, when you have Swift API. Thats why you should use Swift's Dictionary. How? 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"

Upvotes: 5

Related Questions