RajV
RajV

Reputation: 7170

Getting reference to a Dictionary value

I have a need for a data structure somewhat like this.

var d = ["101": [1: "value1"]]

I need to modify the inner Dictionary. I can do that using a function:

func changeIt(inout dict: [Int:String]) {
    dict[1] = "value2"
}

changeIt(&d["101"]!)

Edit: I can also do this:

d["101"]![1] = "value3"

But I will like to make this change without calling another function. Something like this.

var sub = &d["101"]! //Does not compile

sub[1] = "value3"

Is there anyway of doing this?

Upvotes: 5

Views: 2257

Answers (1)

matt
matt

Reputation: 535140

You can't do it in a single move except by calling a function with an inout parameter, as you've already shown. Otherwise you cannot take a "reference" to a value type in Swift. The normal way is the old-fashioned, simple way, one step at a time: you pull out the inner dictionary, change it, and put it back again:

let key = "101"
var d = ["101": [1: "value1"]]
if var d2 = d[key] {
    d2[1] = "value2"
    d[key] = d2
}

It's boring but reliable.

Upvotes: 4

Related Questions