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

Time:02-03

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.

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.

CodePudding user response:

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.

  • Related