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
What is the equivalent of a Java HashMap<String,Integer> in Swift
提问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.Map
interface whereas getValue()
is a method of the java.util.Map.Entry
interface.
注意: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)
}