TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.