Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoclosure that takes arguments but doesnot return value

Tags:

closures

swift

The function of autoclosure according to Swift docs states that

An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it.

But when i create a function that takes autoclosure

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

Even the syntax is valid and i can pass the value i cannot use the String value inside the statement. So, is this something swift is missing. May be it should show some error warning while defining the Arguments.

Or am i missing something about autoclosures?

like image 757
Costello Avatar asked Aug 03 '17 17:08

Costello


1 Answers

So... you're sort of misunderstanding how these work. Try to think of autoclosure as delaying execution. I think you're viewing it more as a pass through of values to another function which isn't what it's doing. Check out this example:

// 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"))

Hope this helps clear some stuff up. :D

like image 194
Joe Susnick Avatar answered Nov 25 '22 18:11

Joe Susnick