gpt4 book ai didi

closures - 如何调用传递给函数的闭包?

转载 作者:搜寻专家 更新时间:2023-11-01 06:49:18 25 4
gpt4 key购买 nike

我怀疑我在这里遗漏了一些非常明显的错误,如果我有点厚,请原谅我。

我看到的所有闭包示例都是将闭包传递给数组映射函数。我想编写自己的函数,它需要一个闭包

这就是我想要的

func closureExample(numberToMultiply : Int, myClosure : (multiply : Int) -> Int) -> Int
{
// This gets a compiler error because it says myClosure is not an Int
// I was expecting this to do was to invoke myClosure and return an Int which
// would get multiplied by the numberToMultiply variable and then returned
return numberToMultiply * myClosure
}

我完全不知道我做错了什么

请帮忙!!

最佳答案

与调用任何函数的方式相同,使用 ()

return numberToMultiply * myClosure(multiply: anInteger)

一个工作示例:

func closureExample(numberToMultiply : Int, myClosure : (multiply : Int) -> Int) -> Int {
return numberToMultiply * myClosure(multiply: 2)
}

closureExample(10, { num in
return 2*num
}) // 40

关于closures - 如何调用传递给函数的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24211591/

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