根据Swift docs的自动关闭功能指出:
但是当我创建一个需要自动关闭的功能时
func test(_ clsr:@autoclosure(String)->(String)){
let res = clsr("Hello World")
print(res)
}
test("Good Morning")
即使语法是有效的,我也可以传递值,但不能在语句内使用String值。因此,这是缺少一些快捷方式吗?可能是在定义参数时显示一些错误警告。
还是我缺少有关自动关闭功能的信息?
最佳答案
所以...您有点误解了它们的工作原理。尝试将自动关闭视为延迟执行。我认为您将其更多地看作是将值传递给另一个函数,这并不是它的作用。看看这个例子:
// 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"))
希望这有助于清除一些东西。 :D
关于swift - 自动闭包,接受参数但不返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45490743/