自动闭包

自动闭包是一种自动创建的闭包,用于包装传递给函数作为参数的表达式。

这种闭包不接受任何参数,当它被调用的时候,会返回被包装在其中的表达式的值。

在声明时,需要@autoclosure指定自动闭包

// customersInLine is ["Ewa", "Barry", "Daniella"]
func serve(customer customerProvider: @autoclosure () -> String) {
    print("Now serving \(customerProvider())!")
}
serve(customer: customersInLine.remove(at: 0))

过度使用 autoclosures 会让你的代码变得难以理解

最后更新于