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

新手上路,请多包涵

我有一个用 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.

原文由 Juventus 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 771
2 个回答

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

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

或者试试这个使用类型推断

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

至于for循环

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

原文由 Dew Time 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 Alexander 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题