【问题标题】:How to call a closure passed into a function?如何调用传递给函数的闭包?
【发布时间】:2014-06-13 18:19:01
【问题描述】:

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

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

这就是我正在尝试的

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(1)

标签: closures swift


【解决方案1】:

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

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

【讨论】:

  • 我接受了这个作为答案,因为它在语法上是正确的,即它具有变量名 myClosure(multiply:2) 而不是 myClosure(2)。我不知道我在想什么,我期望传入的闭包封装了调用函数时传入的变量。现在很明显,情况并非如此
  • 我补充说,当我在操场上运行它时,只是为了确定 :)
  • 我还要感谢所有回复的人。这个网站的成员总是非常乐于助人。还有其他人觉得游乐场有点马车吗?
【解决方案2】:

您将闭包参数视为以参数名称命名的函数。 myClosure 是需要对numberToMultiply 进行操作的闭包,所以你想要:

return myClosure(numberToMultiply)

这会将 numberToMultiply 传递给您的闭包,并返回返回值。

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多