In Swift, the method has finally become a "first-class citizen", which can be used as a parameter, and before contacting today's content, you must understand the concepts of methods and closures in Swift. Swift supports methods nesting, and the methods and closures in swift differ in type. This means that the parameters of the incoming method type can also receive closures, but the method can only pass in the parameters of the matching method return value type, that is, before running the method, you need to execute the method in the parameter to calculate the return value in the incoming parameter run call this parameter method, if in a method using multiple judgment statements can be interrupted prematurely, So many times you don't need to know the exact values of the arguments that follow, such as the following example
func expensiveMethod() -> Bool{ NSThread.sleepForTimeInterval(10.0) println("执行了很久") returntrue }
Another method and requires the passing of two parameters of type bool:
and(first:Bool,second:Bool)->Bool{ println("执行and方法") returnfirst&&second }
Now call to try:
resultand(falsesecond: expensiveMethod())
You will find that the speed is very slow, because the Expensivemethod method first runs the method body that calculates the return value and then executes the and method. Central Console Printing:
Executed for a long time
Execute and method
It is possible to change the second parameter to a method that returns a bool type and then pass in a closure if the result of the and method can be executed only by the first argument:
and(first:Bool,getSecond:()->Bool)->Bool{ if !first{ returnfalse }else{ return getSecond() } }
The calling method also needs to be modified:
let=and(falsereturnself.expensiveMethod()})
Such modifications run faster, but when programmers use this API, they need to write a complete closure structure, which is a hassle, and @autoclosure comes in handy. Use this modifier to make the API call enter a return value:
and(first:Bool,@autoclosure getSecond:()->Bool)->Bool{ if !first{ returnfalse }else{ return getSecond() } }
This simplifies the input when it is called:
letand(false, getSecond: expensiveMethod())
It is important to note that @autoclosure can only be used in ()->t with no parameter closures
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Improve swift code quality with @autoclosure