Isaac To
Isaac To

Reputation: 739

How can a value of a value type in a dictionary be modified through an optional of it?

Array and optional types are both a value type in Swift. As exhibited in the following example, one can't modify an array through an optional of it.

var a = [1, 2]
var aOptional: [Int]? = a
aOptional![1] = 100

a remains to be [1, 2] though the array wrapped in aOptional is changed to [1, 100].

With that said, can anyone explain to me how can the following piece of code work?

var testScores = ["Dave": [86, 82, 84]]
testScores["Dave"]![0] = 91

It produces the result that the "Dave" array in testScores to be [91, 82, 84]. The "Dave" array inside testScores is modified through an optional of it, testScores["Dave"]. How is this possible?

Upvotes: 0

Views: 77

Answers (1)

Nirav D
Nirav D

Reputation: 72410

Array in Swift are value type not reference type both a and aOptional are point to different address not the same. You can confirm it using printing address.

var a = [1, 2]
var aOptional: [Int]? = a
aOptional![1] = 100
withUnsafePointer(to: &a) {
    print("Array \(a) has address: \($0)")
}
withUnsafePointer(to: &aOptional) {
    print("Array \(aOptional) has address: \($0)")
}

Output:

Array [1, 2] has address: 0x00007fff5f6c2ae8
Array Optional([1, 100]) has address: 0x00007fff5f6c2ae0
//Both are pointing different memory address

Now with your dictionary you are wrapping the optional with ! and changing the value of same array if you assign it different array then result will same like a and aOptional.

var testScores = ["Dave": [86, 82, 84]]
withUnsafePointer(to: &testScores["Dave"]!) {
    print("Address: \($0)")
}
testScores["Dave"]![0] = 91
print(testScores)
var array = testScores["Dave"]!
array[0] = 100
withUnsafePointer(to: &array) {
    print("New Array Address: \($0)")
}
print(testScores)

Output:

Address: 0x00007fff5a442ac0
["Dave": [91, 82, 84]]
New Array Address: 0x00007fff5a442ae0
["Dave": [91, 82, 84]] //As you can see array's first object is still 91

Upvotes: 2

Related Questions