什么是Swift中的Java HashMap <String,Integer>

Juv*_*tus 13 java dictionary swift swift3

我有一个用Java编写的示例,我想将其转换为Swift.下面是代码的一部分.如果你能提供帮助我真的很感激.

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();
    ...
}
Run Code Online (Sandbox Code Playgroud)

注意:entrySet()java.util.Map接口getValue()的方法,而java.util.Map.Entry接口的方法.

Dew*_*ime 33

我相信你可以使用字典.这里有两种方法可以完成字典部分.

var someProtocol = [String : Int]()
someProtocol["one"] = 1
someProtocol["two"] = 2
Run Code Online (Sandbox Code Playgroud)

或尝试使用类型推断

var someProtocol = [
    "one" : 1,
    "two" : 2
]
Run Code Online (Sandbox Code Playgroud)

至于for循环

var index: Int
for (e, value) in someProtocol  {
    index = value
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ica 6

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

for (word, integer) in stringIntMapping {
    //...
    print(word, integer)
}
Run Code Online (Sandbox Code Playgroud)