sapi
sapi

Reputation: 10224

Can you append to an array inside a dict?

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

Upvotes: 4

Views: 1142

Answers (1)

cncool
cncool

Reputation: 1026

Try unwrapping the array instead of casting:

dict[1]!.append(0)

Upvotes: 2

Related Questions