[英]Trailing closure issue in swift?
Hello i have a created a function which accepts last argument as closure. 您好,我创建了一个函数,该函数接受最后一个参数作为闭包。
func sum(from: Int, to: Int, f: (Int) -> (Int)) -> Int {
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}
Now i when i call this function.One way to call this function is below like this . 现在我当我调用此函数时。如下所示是调用此函数的一种方法。
sum(from: 1, to: 10) { (num) -> (Int) in
return 10
}
I have seen one of the concepts in swift as trailing closure.With trailing closure i can call the function like this . 我已经将swift的概念之一视为尾随闭包。有了尾随闭包,我可以像这样调用函数。
sum(from: 1, to: 10) {
$0
}
but i don't know why it is able to call without any return statement.please tell me how it is happening ? 但是我不知道为什么它可以在没有任何return语句的情况下调用。请告诉我它是如何发生的?
There really is no answer here except "because the language allows it." 除了“因为语言允许”以外,这里真的没有答案。 If you have a single expression in a closure, you may omit the
return
. 如果闭包中只有一个表达式,则可以省略
return
。
The section covering this is "Implicit Returns from Single-Expression Closures" from The Swift Programming Language. 涵盖这一部分的内容是来自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:
单表达式闭包可以通过从声明中省略return关键字来隐式返回其单表达式的结果,如上一个示例的此版本所示:
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.
在这里,sorted(by :)方法的参数的函数类型清楚地表明,闭包必须返回Bool值。 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.
因为闭包的主体包含返回Bool值的单个表达式(s1> s2),所以没有歧义,可以省略return关键字。
This has nothing to do with trailing closure syntax, however. 但是,这与尾随闭包语法无关。 All closures have implicit returns if they are single-expression.
如果所有闭包都是单表达式,则它们都具有隐式返回。
As @rob-napier states, you can do it just because the language allows it. 正如@ rob-napier所说,您可以这样做只是因为语言允许它。
But, note your example is also doing two different things in that last part: 但是,请注意,您的示例在最后一部分中还将做两件事:
sum(from: 1, to: 10) {
$0
}
Not only are you omitting the return
statement, you're also omitting the named parameters, so the $0
is not dependant on the omitting the return
feature. 您不仅要省略
return
语句,而且还要省略命名参数,因此$0
并不取决于省略return
功能。
This would be a more accurate example for just omitting return
: 这只是省略
return
的更准确的示例:
sum(from: 1, to: 10) { (num) -> (Int) in
num
}
That said, I wouldn't recommend using either of these features
. 就是说,我不建议您使用其中任何一个
features
。 In most cases, it's better to make the code easier to read later. 在大多数情况下,最好使代码稍后易于阅读。 Your future self (and others who use the code after you) will thank you.
您未来的自我(以及在您之后使用该代码的其他人)将感谢您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.