UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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]
temp!.append("eagle")
myDictionary[3] = temp

print(myDictionary)

// [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!

2      

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.

3      

You could also use optional chaining

myDictionary[3]?.append("eagle")

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

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.