Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do put multiple values into a single key in Swift?

Is there a way to put multiple values in one key in Swift’s dictionary, such as ‘multimap’ in Java?

var multiDic = [String:UserData]()

This is the dictionary I declared. it has this structure.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct UserData{
    var name: String
    var id: String
    var nickname: String
}

And when I put the value in one key in the dictionary, the value is updated without being stacked.

for key in 1...10 {
    multiDic.updateValue(UserData(name:"name+\(key)", id:"id+\(key)", nickname:"nick+\(key)"), forKey: "A")
}

print(multiDic.count)

reults
1

How can I accumulate multiple values on a single key? I looked up a library called ‘Buckets’
(https://github.com/mauriciosantos/Buckets-Swift#buckets), but there has been no update since swift 3.0.

>Solution :

Swift dictionary doesn’t support this. One work around is to declare the dictionary to hold an array of values, like this:

var multiDic = [String:[UserData]]()

You would have to modify your code for adding values to work with the array instead of updating the value in place.

I haven’t tried the "Buckets" project you mention, but for what it’s worth, it probably still works either as-is or with minor changes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading