请考虑以下代码:
let dict = [ "key1" : 1, "key2" : 2, "key3" : 3, "key4" : 4, "key5" : 5 ] let array = dict.map{$0} for item in array { print(item) }
你从print语句得到的是:
("key2", 2) ("key3", 3) ("key4", 4) ("key5", 5) ("key1", 1)
字典中的键/值对将转换为元组.我原本期望得到一系列单值词典.
为什么map语句将我的项目转换为元组,这种行为记录在哪里?
使用以下代码将元组数组转换回字典数组是一件简单的事情:
let array = dict.map{[$0.0:$0.1]}
...但我试图理解为什么地图首先给我元组.
这是其中的一部分DictionaryIterator
.请参阅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