Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 532
Juventus Avatar asked Jun 19 '17 18:06

Juventus


People also ask

Does Swift have HashMap?

Swift uses the SipHash hash function to handle many of the hash value calculations. The API to this implementation is private, but a public implementation has been done here.

What is HashMap in Swift?

A hash table is a data structure that groups values to a key. As we've seen, structures like graphs, tries and linked lists follow this widely-adopted model. In some cases, built-in Swift data types like dictionaries also accomplish the same goal.

Can HashMap key be an integer?

Here, keys are used as identifiers which are used to associate each value on a map. It can store different types: Integer keys and String values or same types: Integer keys and Integer values. HashMap is similar to HashTable, but it is unsynchronized.

What is the best alternative for HashMap in Java?

Whereas, ConcurrentHashMap is introduced as an alternative to the HashMap. The ConcurrentHashMap is a synchronized collection class. The HashMap is non-thread-safe and can not be used in a Concurrent multi-threaded environment.


2 Answers

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 } 
like image 143
Dew Time Avatar answered Sep 24 '22 17:09

Dew Time


let stringIntMapping = [     "one": 1,     "two": 2, ]  for (word, integer) in stringIntMapping {     //...     print(word, integer) } 
like image 28
Alexander Avatar answered Sep 22 '22 17:09

Alexander