Nasiba
Nasiba

Reputation: 331

How to append an array with a value at particular index for a key in NSMutableDictionary in Swift

I would like to know how to append an array with a value at particular index for a key in NSMutableDictionary in Swift?

I have a dictionary as follows:

let xyz: NSMutableDictionary = ["1":[1,2,3,4,"1","n"],"2":[1,2,3,4,"+","o","6","2"]]

I want to add to key "1" a value of 1 at index 6 i.e. It should look like:

let xyz: NSMutableDictionary = ["1":[1,2,3,4,"1","n",1],"2":[1,2,3,4,"+","o","6","2"]]

How to do it?

Upvotes: 2

Views: 985

Answers (3)

dfrib
dfrib

Reputation: 73196

If you choose the method to (for a given key, in your example "1")

  • extract a mutable copy the value array,
  • mutate this copy,
  • overwrite the original array (value) for the given key,

you need to tell (in this case, attempt to cast) Swift that that the value array is an array of instances of type AnyObject (i.e., [AnyObject]), otherwise, as per default, the key will be extracted as a single AnyObject. Only for the former will Swift realize we can append elements (to an array), whereas for the latter, Swift wont allow us to append elements to a single AnyObject value (even if it wraps an array).

E.g.

let xyz: NSMutableDictionary = ["1":[1,2,3,4,"1","n"],"2":[1,2,3,4,"+","o","6","2"]]

let appendValue = "1"
let forKey = "1"
if var arr = xyz[forKey] as? [AnyObject] {
    arr.append(appendValue)
    xyz[forKey] = arr
}

resulting in

print(xyz)

{
    1 =     (
        1,
        2,
        3,
        4,
        1,
        n,
        1
    );
    2 =     (
        1,
        2,
        3,
        4,
        "+",
        o,
        6,
        2
    );
}

Upvotes: 1

Witterquick
Witterquick

Reputation: 6140

Something like

var res = xyz["1"] //the result is the array
res.append(1) // assuming you can change the array

If you can't change the array, you will need something like

var res = xyz["1"]
var newArr = res
newArr.append(1)
xyz["1"] = newArr

Upvotes: 0

gnasher729
gnasher729

Reputation: 52592

Your dictionary contains key / value pairs. The values or arrays. You want to change one of the values. To do that, if the value itself (the array) is modifiable then you read the value for the key "1", and modify it. If the value is not modifiable, then you read the old value for the key "1", create a new array containing what you want it to contain, and store that new value again under the key "1".

Upvotes: 0

Related Questions