Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating dictionary in Swift

I guess I noticed a bug in the Swift Dictionary enumeration implementation.

The output of this code snippet:

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
   print("Dictionary key \(key) - Dictionary value \(value)")
}

should be:

Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One

instead of:

Dictionary key 0 - Dictionary value (key: 2, value: "Two")
Dictionary key 1 - Dictionary value (key: 3, value: "Three")
Dictionary key 2 - Dictionary value (key: 1, value: "One")

Can anyone please explain this behavior?

like image 457
Jayram Kumar Avatar asked Sep 09 '18 16:09

Jayram Kumar


People also ask

How do I iterate through a dictionary in Swift?

The forEach() method is used to iterate through each element of a dictionary.

What does enumerated mean in Swift?

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. If you are familiar with C, you will know that C enumerations assign related names to a set of integer values.

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.

How does dictionary work in Swift?

Swift 4 dictionaries use unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike items in an array, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers.


1 Answers

It's not a bug, you are causing the confusion because you are using the wrong API.

You get your expected result with this (dictionary related) syntax

for (key, value) in someDict { ...

where

  • key is the dictionary key
  • value is the dictionary value.

Using the (array related) syntax

for (key, value) in someDict.enumerated() { ...

which is actually

for (index, element) in someDict.enumerated() { ...

the dictionary is treated as an array of tuples and

  • key is the index
  • value is a tuple ("key": <dictionary key>, "value": <dictionary value>)
like image 151
vadian Avatar answered Nov 14 '22 11:11

vadian