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.
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.
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.
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.
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.
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 }
let stringIntMapping = [ "one": 1, "two": 2, ] for (word, integer) in stringIntMapping { //... print(word, integer) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With