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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44637836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:38:47  来源:igfitidea点击:

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

javaswiftdictionaryswift3

提问by Juventus

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.

我有一个用 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();
    ...
}

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

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

采纳答案by Dew Time

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

至于 for 循环

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

回答by Mykola Yashchenko

I guess it will be something like that:

我想它会是这样的:

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

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

回答by Alexander - Reinstate Monica

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

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