简体   繁体   English

Swift-函数参数中的闭包

[英]Swift - Closures in function arguments

I'm new to iOS and swift, trying to understand the basics. 我是iOS的新手,并且想了解基本知识。 I tried the below two function calls in playground and I was expecting the result to be same but the first one returned one value and the second one returned two values. 我在操场上尝试了以下两个函数调用,但我期望结果是相同的,但是第一个返回一个值,第二个返回两个值。

Would you be able to explain me why? 您能解释一下为什么吗?

func sqrt(a: Float) -> Float {
    return a * a
}

func avgOfSqrts(a: Float, b: Float, f: (Float -> Float)) -> Float {
    return (f(a) + f(b))/2
}

avgOfSqrts(2,3,sqrt) //returns 6.5

avgOfSqrts(2, 3, {x in return x * x}) //returns 4.0 and 9.0

shouldn't the function call with closure return 6.5 as well? 具有闭包的函数调用也不应该返回6.5吗?

Thanks! 谢谢!

But the results are the same. 但是结果是一样的。 You can try assign it to a var 您可以尝试将其分配给var

var result = avgOfSqrts(2, 3, {x in return x * x})
result //this is 6.5 as expected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM