Search code examples
iosswiftmultimapswift-dictionary

Swift how can I make Multimap(Java)


I begin Swift and IOS development, so I'm very new to this, I make what I want in java (See example) but I can't find how to do in Swift I want to make a dictionary on Swift , I know that I can make it like this

var dict = Dictionary<String, Array<String>>()

var s1 = "one"
var s2 = "two"
var s3 = "three"
var root = "numbers"
dict[root] = [s1,s2,s3]

for str in dict
{
    print(str.value)
}

But this isn't that I want. I make same thing in java like this

final TreeMultimap<String, String> third1000multi = TreeMultimap.create(Ordering.<String>natural(), Ordering.<String>natural());
for (Word w : third1000) {
            third1000multi.put(w.getType(), w.getWord());
        }

It must be create a key if there isn't a key like this , if there is key , it must add the value to the key. For example,

  1. "choose" --> "choosing" (there isn't any key "choose" so create one and put it "choosing" value choose = ["choosing"] )

2."choose"--> choosen (there is a key named " choose" so add this value in it. choose = ["choosing","choosen"] Thanks for your help :)


Solution

  • You can make use of the Dictionary subscript(_:default:) accessor.

    var dict = [String:[String]]()
    
    var words = [ "one", "two", "three"]
    var root = "numbers"
    
    for word in words {
        dict[root, default: []].append(word)
    }
    print(dict)
    

    Or more closely to your Java code:

    var third1000multi = [String:[String]]()
    for w in third1000 {
        third1000multi[w.type, default: []].append(w.word)
    }