gg1789
gg1789

Reputation: 31

Accessing Arrays in Dictionaries (swift)

I can't seem to find a solution for how to type out the syntax. I want to access and be able to modify individual integers within an array that's nested in a larger dictionary.

Here's an example:

var exampleDictionary = [ 1: [2,3] , 2: [4,5] , 3: [7,8] ]

print (exampleDictionary[2]!)   // prints [4,5]

How can I access the first value of Key 2 (4 above)?

How can I change just the first value of Key 2?

I'm trying things like this and it's not working:

exampleDictionary[2[0]] = (exampleDictionary[2[0]] - 3) // want to change [4,5] to [1,5]
print (exampleDictionary[2[0]])  // should print "1"

exampleDictionary[2 : [0]] = (exampleDictionary[2 :[0]] - 3)
print (exampleDictionary[2 : [0]])

Upvotes: 0

Views: 77

Answers (3)

Mohammad Reza Koohkan
Mohammad Reza Koohkan

Reputation: 1734

First of all you have dictionary of type [Int: [Int]], which means every key have a value of array from Int.

1.If your exampleDictionary is of unrelated type, Specify the type of exampleDictionary to [Int: [Int]] so that you won't need to cast it in next step.

var exampleDictionary: [Int: [Int]] = [ 1: [2,3] , 2: [4,5] , 3: [7,8] ]

2.Access the key you want.

var key2: [Int] = exampleDictionary[2]!

var firstValueOfKey2: Int = key2.first!

3.Change the value for key2:

key2 = [1,5]

4.Because of Swift, Collections are value type which means that a pointer refers to new block in memory, this means that you cant change the value from root object directly from modifiers. then you should assign the last result to root object.

exampleDictionary[2] = key2

Upvotes: 0

vadian
vadian

Reputation: 285039

You have always to consider that Swift collection types are value types and you have to modify the object in place, something like

if let firstValueOfKey2 = exampleDictionary[2]?.first {
    print(firstValueOfKey2)
    exampleDictionary[2]!.first = firstValueOfKey2 - 3
    print(exampleDictionary[2]!.first!)
}

Upvotes: 0

ielyamani
ielyamani

Reputation: 18581

You should subscript the array not its index :

exampleDictionary[2]![0] = (exampleDictionary[2]?[0] ?? 0) - 3

Safer would be to use optional binding like so:

if var array = exampleDictionary[2] {
    array[0] -= 3
    exampleDictionary[2] = array
}

Upvotes: 4

Related Questions