Swift Closure为什么调用函数返回错误?

Chr*_*ris 3 closures function ios swift

只是学习闭包和嵌套功能.鉴于下面的嵌套函数:

func printerFunction() -> (Int) -> () {
    var runningTotal = 0
    func printInteger(number: Int) {
        runningTotal += 10
        println("The running total is: \(runningTotal)")
    }
    return printInteger
}
Run Code Online (Sandbox Code Playgroud)

为什么调用func本身有错误,但是当我将func分配给常量时没有错误?printAndReturnIntegerFunc(2)将2 Int作为参数传递给返回值?

printerFunction(2) // error
let printAndReturnIntegerFunc = printerFunction() 
printAndReturnIntegerFunc(2) // no error. where is this 2 going??
Run Code Online (Sandbox Code Playgroud)

Dha*_*esh 6

首先,你在这里得到错误,printerFunction(2)因为printerFunction不能接受任何参数,如果你想给出一个参数,那么你可以这样做:

func printerFunction(abc: Int) -> (Int) -> (){


}
Run Code Online (Sandbox Code Playgroud)

这将工作正常:

printerFunction(2)
Run Code Online (Sandbox Code Playgroud)

之后,您将该函数的引用提供给另一个变量,如下所示:

let printAndReturnIntegerFunc = printerFunction() 
Run Code Online (Sandbox Code Playgroud)

这意味着类型printAndReturnIntegerFunc是这样的:

在此输入图像描述

这意味着它接受一个Int,它将返回void,所以这将工作:

printAndReturnIntegerFunc(2)
Run Code Online (Sandbox Code Playgroud)


Eri*_*ian 5

(1)函数签名printerFunction() -> (Int) -> ()表示它不带参数并返回另一个函数,这就是为什么当你尝试printerFunction(2)用参数调用时会给你一个错误.
(2)返回函数的签名(Int) -> ()意味着它接受Int的一个参数并返回Void.所以printAndReturnIntegerFunc(2)工作