Autoclosure接受参数但不返回值

Cos*_*llo 6 closures swift

根据Swift博士的说法,autoclosure的功能表明了这一点

autoclosure是一个自动创建的闭包,用于包装作为参数传递给函数的表达式.它不接受任何参数,当它被调用时,它返回包含在其中的表达式的值.

但是当我创建一个需要autoclosure的函数时

func test(_ clsr:@autoclosure(String)->(String)){
   let res = clsr("Hello World")
   print(res)
}
test("Good Morning")
Run Code Online (Sandbox Code Playgroud)

即使语法有效,我也可以传递值,我不能在语句中使用String值.那么,这件事是不是很快就会丢失.也许它应该在定义参数时显示一些错误警告.

或者我错过了关于autoclosures的事情?

Joe*_*ick 2

所以...你有点误解了它们是如何工作的。尝试将自动关闭视为延迟执行。我认为您更多地将其视为将值传递给另一个函数,但这不是它正在做的事情。看看这个例子:

// Takes a function that has already been provided with arguments and then executes it and prints the result
func printAfterEvaluating(closure: @autoclosure () -> String) {
    let result = closure()
    print(result)
}

// A very basic function that returns a string
func returnAString(_ argument: String) -> String {
    return argument
}

// Calling the function with the other function as an argument.
printAfterEvaluating(closure: returnAString("Foo"))
Run Code Online (Sandbox Code Playgroud)

希望这有助于澄清一些事情。:D