4

Consider the code below:

let dict = [
  "key1" : 1,
  "key2" : 2,
  "key3" : 3,
  "key4" : 4,
  "key5" : 5
]

let array = dict.map{$0}
for item in array {
  print(item)
}

What you get from the print statements is:

("key2", 2)
("key3", 3)
("key4", 4)
("key5", 5)
("key1", 1)

The key/value pairs from the dictionary are converted to tuples. I would have expected to get back an array of single-value dictionaries.

Why does the map statement convert my items to tuples, and where is this behavior documented?

It's a simple matter to convert the array of tuples back to an array of dictionaries using this code:

let array = dict.map{[$0.0:$0.1]}

...but I'm trying to understand why map gives me tuples in the first place.

JAL
  • 41,701
  • 23
  • 172
  • 300
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Not my downvote, but I would guess it is due to lack of research. I found the answer by command-clicking `Dictionary` and searching for `iterator` in the module. – JAL Jan 17 '17 at 14:38
  • 1
    I'm at a disadvantage here because I don't know what to search *for*. I did spend at least 1/2 hour trying to figure it out, and failed. I did not realize that the map function depends on an iterator of Dictionary. It makes sense now that I know that, but I had no idea what to look for. – Duncan C Jan 17 '17 at 14:41
  • 1
    ¯\\_(ツ)_/¯ It's Stack Overflow, I gave up on questioning drive-bye downvotes. – JAL Jan 17 '17 at 14:42
  • 1
    I don't mind getting down-voted if my question or answer is somehow lacking - as long as someone posts a constructive criticism. Drive-by downvotes really annoy me however. – Duncan C Jan 17 '17 at 14:44

1 Answers1

8

It's part of DictionaryIterator<Key, Value>. See the comment in the HashedCollections module for makeIterator:

/// Returns an iterator over the dictionary's key-value pairs.
///
/// Iterating over a dictionary yields the key-value pairs as two-element
/// tuples. You can decompose the tuple in a `for`-`in` loop, which calls
/// `makeIterator()` behind the scenes, or when calling the iterator's
/// `next()` method directly.
///
///     let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
///     for (name, hueValue) in hues {
///         print("The hue of \(name) is \(hueValue).")
///     }
///     // Prints "The hue of Heliotrope is 296."
///     // Prints "The hue of Coral is 16."
///     // Prints "The hue of Aquamarine is 156."
///
/// - Returns: An iterator over the dictionary with elements of type
///   `(key: Key, value: Value)`.
public func makeIterator() -> DictionaryIterator<Key, Value>
JAL
  • 41,701
  • 23
  • 172
  • 300