gpt4 book ai didi

swift - 对 .map 转换闭包的困惑

转载 作者:行者123 更新时间:2023-11-28 13:36:46 25 4
gpt4 key购买 nike

下面的代码编译和运行正常,似乎表明 closureString.init(describing:) 函数在它们的签名中是完全等价的,因为 .map 方法愉快地接受了它们。

let someDict: [String: String] = [
"string1" : "Hello",
"string2" : "Bye",
]

//One way to call .map
var closure = { (key: String, value: String) -> String in
return "The key is \(key), the value is \(value)"
}
someDict.map(closure)

//Another way to call .map
someDict.map(String.init(describing:))

但是如何在 .map 中放置一个 String.init(describing:) 函数,该函数只有一个参数,而 . map 需要一个有两个参数的函数?或者我在这里误解了什么..

顺便说一句,检查文档表明它确实需要一个有 2 个参数的函数:

transform: ((key: String, value: String)) throws -> T

最佳答案

Btw, checking the documentation shows that it really does expect a function of 2 arguments:

transform: ((key: String, value: String)) throws -> T

实际上,没有。请注意额外的括号 ()。它表明它需要一个接受一个参数的函数,该参数是一个包含两个元素的元组。

考虑这个例子:

// function foo takes two arguments
func foo(_ a: Int, _ b: Int) -> Int {
return a + b
}

// function bar takes one tuple with two elements
func bar(_ a: (Int, Int)) -> Int {
return a.0 + a.1
}

let f1 = foo
print(type(of: f1)) // (Int, Int) -> Int

let f2 = bar
print(type(of: f2)) // ((Int, Int)) -> Int

因此,额外的括号告诉我们 map 需要一个参数,该参数是一个包含两个元素的元组。

传递给 map 的闭包总是一次对序列中的单个元素进行操作。该元素可以是一个元组,例如您的案例,然后您的闭包可以解构该元组为多个值。

考虑这个例子:

// tup is a tuple containing 3 values
let tup = (1, true, "hello")

// deconstruct the tuple through assignment
let (x, y, z) = tup

print(x) // 1
print(y) // true
print(z) // hello

所以在这个例子中:

var closure = { (key: String, value: String) -> String in
return "The key is \(key), the value is \(value)"
}
someDict.map(closure)

map 的闭包被赋予一个形式为 (key: String, value: String) 的元组,闭包正在将其解构为 keyvalue 就像上面的 let 所做的那样。

在这个例子中:

someDict.map(String.init(describing:))

相当于:

someDict.map({ String(describing: $0) })

map 获取整个元组并将其传递给 String(describing:)

关于swift - 对 .map 转换闭包的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511395/

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