NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Writing to an array inside a dictionary?

Forums > Swift

Hi, happy Friday!

I was working with some data of type <Int, [String]>

Here's a sample data,

var myDictionary: Dictionary<Int, [String]> = [
1: ["apple", "banana", "cranberries"],
2: ["tiger", "dog", "cat"],
3: ["crow", "goose", "sparrow"]

Now, what I want to do is to add a new item to an array of a specified key. (e.g. add "eagle" to myDictionary[3])

I do have a code that works but as you can see, I had to manually read and write the values by declaring a new variable.

var temp = myDictionary[3]
myDictionary[3] = temp


// [1: ["apple", "banana", "cranberries"],  2: ["tiger", "dog", "cat"], 3: ["crow", "goose", "sparrow", "eagle"],]

I was wondering if this is the only way to write to an array inside a dictionary, or if there's one-line command that does the same work. Thank you!


myDictionary[3, default: []].append("eagle")

This will fetch the item with key of 3 or return an empty array [] if that key doesn't exist in myDictionary.

Then it appends a new value either to the returned array corresponding to the key 3 or to the empty array [].

Finally, it sets the value of the key 3 to the newly appended array.


You could also use optional chaining


where if 3 is a key, then it will extract the array and append "eagle" else it will return nil


Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.