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

标签 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]}

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

最佳答案

它是 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>

关于swift - 为什么 Dictionary.map 返回一个元组数组,它​​在哪里记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41687593/

相关文章:

PHP:寻找类似 Java Stream API 的东西

swift - 授予通知访问权限后执行 segue

java - 如果存在特定键 Java 8 的值,则检查列表映射

javascript - 使用 JavaScript 从字典中的键获取最接近给定数字的值

C# 字典到 C++ std::map

list - 类似映射的函数,在循环中的每次迭代中返回多个值

ios - 具有固定宽度的居中按钮会中断 NSLayoutConstraint

ios - 如何在 JSQMessagesViewController Swift 4 中添加用户图像

iOS swift : How to prepare a cell for reuse

swift - 这两种表达 map 功能的方式不是等效的吗?