What is the equivalent of a Java HashMap<String,Integer> in Swift

梦想的初衷 提交于 2019-12-22 02:31:20

问题


I have an example written in Java that I would like to convert into Swift. Below is a section of the code. I would really appreciate if you can help.

Map<String, Integer> someProtocol = new HashMap<>();
someProtocol.put("one", Integer.valueOf(1));
someProtocol.put("two", Integer.valueOf(2));

for (Map.Entry<String, Integer> e : someProtocol.entrySet() {
    int index = e.getValue();
    ...
}

NOTE: entrySet() is a method of the java.util.Map interface whereas getValue() is a method of the java.util.Map.Entry interface.


回答1:


I believe you can use a dictionary. Here are two ways to do the dictionary part.

var someProtocol = [String : Int]()
someProtocol["one"] = 1
someProtocol["two"] = 2

or try this which uses type inference

var someProtocol = [
    "one" : 1,
    "two" : 2
]

as for the for loop

var index: Int
for (e, value) in someProtocol  {
    index = value
}



回答2:


let stringIntMapping = [
    "one": 1,
    "two": 2,
]

for (word, integer) in stringIntMapping {
    //...
    print(word, integer)
}



回答3:


I guess it will be something like that:

let someProtocol = [
    "one" : 1,
    "two" : 2
]

for (key, value) in someProtocol {
    var index = value
}


来源:https://stackoverflow.com/questions/44637836/what-is-the-equivalent-of-a-java-hashmapstring-integer-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!