gpt4 book ai didi

ios - 切换 map : error: cannot invoke 'map' with an argument list of type '((_) -> _)'

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:37 25 4
gpt4 key购买 nike

我不明白为什么这个有效:

var arr = [4,5,6,7]

arr.map() {
x in
return x + 2
}

虽然这个不是

arr.map() {
x in
var y = x + 2
return y
}

有错误

Playground execution failed: MyPlayground.playground:13:5: error: cannot invoke 'map' with an argument list of type '((_) -> _)' arr.map() {

最佳答案

这里的问题是有错误信息。通常,当您看到类似 cannot invoke .. with ... 的内容时,这意味着编译器的类型推断不起作用。

在这种情况下,您遇到了闭包内推理的局限性之一。 Swift 只能推断单语句闭包的类型,不能推断多语句闭包的类型。在你的第一个例子中:

arr.map() {
x in
return x + 2
}

实际上只有一个语句:return x + 2。然而,在第二个:

arr.map() {
x in
var y = x + 2
return y
}

有一个赋值语句 (var y = x + 2),然后返回。所以这个错误有点误导:它并不意味着你“不能用这种类型的参数调用 map()”,它的意思是说“我不知道 x 或 y 是什么类型”。

顺便说一句,在单语句闭包中,还有另外两件事可以推断出来。返回语句:

arr.map() {
x in
x + 2
}

和变量名本身:

arr.map() { $0 + 2 }

不过,它们都生成相同的编译代码。所以你选择哪一个真的是一个品味问题。 (例如,虽然我认为推断的 return 看起来干净且更易于阅读,但我喜欢 $0,所以我通常总是将 x 放入 或其他内容,即使对于非常短的闭包也是如此。不过,很明显,这取决于你。)

最后一件事:因为这实际上只是语法的东西,所以值得注意的是 () 也不是必需的:

arr.map { x in x + 2 }

正如@MartinR 所指出的,编译器也可以从外部上下文中推断出某些类型:

let b: [Int] = arr.map { x in
var y = x + 2
return y
}

这是值得牢记的。 ( it seems that the "one-statement" rule only applies when there's no other type info available )

关于ios - 切换 map : error: cannot invoke 'map' with an argument list of type '((_) -> _)' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32526386/

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