为什么Dictionary.map返回一个元组数组,它​​在哪里记录?

时间:2017-01-17 01:16:34

标签: swift dictionary map-function

请考虑以下代码:

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

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

您从印刷陈述中得到的是:

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

字典中的键/值对将转换为元组。我原本期望得到一系列单值词典。

为什么map语句将我的项目转换为元组,以及这种行为记录在哪里?

使用此代码将元组数组转换回字典数组是一件简单的事情:

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

...但是我试图理解为什么地图首先给我元组。

1 个答案:

答案 0 :(得分:8)

这是DictionaryIterator<Key, Value>的一部分。请参阅HashedCollections模块中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>