4
votes

In Swift, you can declare a dict where the value is an array type, eg:

var dict: [Int: [Int]] = [:]

However, if you assign an array for a given key:

dict[1] = []

then it appears that Swift treats the array as immutable. For example, if we try:

(dict[1] as [Int]).append(0) // explicit cast to avoid DictionaryIndex

then we get the error 'immutable value of type [Int] has only mutating members named 'append''.


If we explicitly make the array mutable, then the append works, but doesn't modify the original array:

var arr = dict[1]!
arr.append(0) // OK, but dict[1] is unmodified

How can you append to an array which is a dict value?

More generally, how can you treat the values of a dictionary as mutable?


One workaround is to reassign the value afterwards, but this does not seem like good practice at all:

var arr = dict[1]!
arr.append(0)
dict[1] = arr
1
I really wish that we could have a binding close vote on our own questions as dupes. That one didn't show up as related until after submission >< (ie meta.stackexchange.com/questions/172002/…) - sapi

1 Answers

2
votes

Try unwrapping the array instead of casting:

dict[1]!.append(0)