gpt4 book ai didi

swift - 是否有将集合转换为字典的 CollectionType 函数?

转载 作者:可可西里 更新时间:2023-11-01 00:52:21 24 4
gpt4 key购买 nike

在Swift中,有没有类似map()的Collection函数,不是把集合变成数组,而是变成字典?

我想写的一个例子:

let collection = [1, 2, 3, 4, 5] // Could also be a dictionary itself
let dictionary: [Int : String] = collection.map{
$0 : "Number: \($0)"
}

我想没有这样的功能,类似但优雅的东西会是什么样子?

最佳答案

下面是如何完成的草图。它使用从元素闭包返回的元组,而不是您的 f1($0) : f2($0) 伪代码。请注意,元组元素可以是任何类型,只要第一个(将用作键)是可哈希的。

let collection = [1, 2, 3, 4, 5] 

/* OP's requested form:
let dictionary: [Int : String] = collection.map{
$0 : "Number: \($0)"
}
*/

// Return a tuple of (key, value) from the closure...
extension CollectionType {
func mapd<Tk: Hashable, Tv>(elementClosure: (Self.Generator.Element) -> (Tk, Tv) ) -> [Tk : Tv] {
var returnDict = [Tk : Tv]()
for i in self {
let (k, v) = elementClosure(i)
returnDict[k] = v
}
return returnDict
}
}

let dictionary: [Int : String] = collection.mapd{ ($0, "Number: \($0)") }
print("\(dictionary)") // "[5: "Number: 5", 2: "Number: 2", 3: "Number: 3", 1: "Number:1]"

// Neither of the dictionary's elements need be the type of the collection,
// it's entirely up to what the closure returns.

let dictionary2: [Double : String] = collection.mapd{ (Double($0), "Number: \($0)") }
print("\(dictionary)") // "[5: "Number: 5", 2: "Number: 2", 3: "Number: 3", 1: "Number:1]"

关于swift - 是否有将集合转换为字典的 CollectionType 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33171129/

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