40

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.

Jack G.
  • 3,681
  • 4
  • 20
  • 24
Juventus
  • 661
  • 1
  • 8
  • 13
  • I have tried to declare someProtocol as NSMutableDictionary but I had difficulties running it through the for loop. – Juventus Jun 19 '17 at 19:22
  • 1
    Side note: in Java you can do `someProtocol.put("one", 1)` – shmosel Jun 19 '17 at 19:27
  • 11
    You shouldn't convert Java to Swift on a line by line level. That limits your code to only using those features in Swift that have a Java analogue. That's a severe restriction that leads to crappy (Java-level) code. You should instead look at what problem the Java code is solving, and then find the best way of soling that problem in Swift. This technique leads to almost universally better code. – Alexander Jun 19 '17 at 19:32
  • OP never said he wants to convert it line by line though. For example, I'm looking for the same thing as OP, and I stumbled onto this. The same or similar approach in a different language has being given to me in the answers - so I'd say it's a valid question as well as a valid problem. +1 – milosmns Apr 10 '20 at 16:15

3 Answers3

71

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
}
Boghyon Hoffmann
  • 17,103
  • 12
  • 72
  • 170
Dew Time
  • 818
  • 9
  • 10
  • 1
    Yep, that's exactly right. I would omit the first code snippet though, as that's a Swift anti pattern (that's especially common for Java programmers who don't know there are literals). Also, `index` should be a variable in the scope of the `for` loop. – Alexander Jun 19 '17 at 19:27
  • 1
    Thank you for providing this response, it really help me out. – Juventus Jun 22 '17 at 11:36
  • what about `LinkedHashMap`? – user924 Mar 28 '19 at 20:46
6
let stringIntMapping = [
    "one": 1,
    "two": 2,
]

for (word, integer) in stringIntMapping {
    //...
    print(word, integer)
}
Alexander
  • 59,041
  • 12
  • 98
  • 151
3

I guess it will be something like that:

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

for (key, value) in someProtocol {
    var index = value
}
Mykola Yashchenko
  • 5,103
  • 3
  • 39
  • 48