【问题标题】:Why does Dictionary.map return an array of tuples, and where is it documented?为什么 Dictionary.map 返回一个元组数组,它​​记录在哪里?
【发布时间】:2023-03-18 01:20:01
【问题描述】:

考虑下面的代码:

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 首先给了我元组。

【问题讨论】:

  • 不是我的反对意见,但我猜这是由于缺乏研究。我通过命令单击Dictionary 并在模块中搜索iterator 找到了答案。
  • 我在这里处于劣势,因为我不知道要搜索什么。我确实花了至少 1/2 小时试图弄清楚,但失败了。我没有意识到 map 函数依赖于 Dictionary 的迭代器。现在我知道这一点是有道理的,但我不知道要寻找什么。
  • ¯\_(ツ)_/¯ 这是堆栈溢出,我放弃了质疑开车再见的投票。
  • 如果我的问题或答案在某种程度上缺乏,我不介意被否决 - 只要有人发表建设性的批评。然而,路过的投票真的让我很恼火。

标签: swift dictionary map-function


【解决方案1】:

它是DictionaryIterator<Key, Value> 的一部分。 makeIteratorHashedCollections 模块中的评论:

/// 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>

【讨论】:

  • 哦,我学到了一些我不知道的东西:元组有标签! for tuple in hues {print(tuple.key)}
  • 另一个有用的事情是这样做:for (key, object) in dict{print(key)}.
猜你喜欢
  • 1970-01-01
  • 2019-12-23
  • 2011-11-25
  • 2022-10-01
  • 2020-07-07
  • 2021-02-08
  • 2019-10-31
  • 1970-01-01
相关资源
最近更新 更多