gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:50:05 25 4
gpt4 key购买 nike

考虑下面的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com