问题
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