gpt4 book ai didi

ios - swift 中的尾随关闭问题?

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

你好,我创建了一个函数,它接受最后一个参数作为闭包。

func sum(from: Int, to: Int, f: (Int) -> (Int)) -> Int {
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}

现在我调用这个函数。调用这个函数的一种方法如下所示。

sum(from: 1, to: 10) { (num) -> (Int) in
return 10
}

我在 swift 中看到了尾随闭包的概念之一。有了尾随闭包,我可以像这样调用函数。

sum(from: 1, to: 10) {
$0
}

但我不知道为什么它可以在没有任何return 语句的情况下调用。请告诉我这是怎么发生的?

最佳答案

除了“因为语言允许”之外,这里真的没有答案。如果闭包中只有一个表达式,则可以省略 return

涵盖此内容的部分是 "Implicit Returns from Single-Expression Closures"来自 Swift 编程语言。

Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration, as in this version of the previous example:

reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

Here, the function type of the sorted(by:) method’s argument makes it clear that a Bool value must be returned by the closure. Because the closure’s body contains a single expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return keyword can be omitted.

然而,这与尾随闭包语法无关。如果闭包是单表达式,则所有闭包都有隐式返回。

关于ios - swift 中的尾随关闭问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490173/

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