Using closures as parameters without trailing closures Swift
When using trailing closure syntax it seems quite easy to pass a function as a parameter of another function.
However I want to do this WITHOUT using the trailing closure syntax
func doSomethingTwo(closure: (String) -> Void) {
closure("AAA")
}
doSomethingTwo(closure: print("TEST") )
gives Cannot convert value of type '()' to expected argument type '(String) -> Void'
I know that
doSomethingTwo{ (test: String) in
print ("\(test)")
}
works, but want this without the trailing closure syntax.
This is not a homework problem, I am looking at tutorials and have done research that has not given me an answer to this question.
You need to define your own print method to pass it as a parameter:
func doSomethingTwo(closure: (String) -> ()) {
// when you call the closure you need to pass the string to be printed
closure("TEST")
}
Define the method to print the string that will be passed to the closure:
let closure: (String) -> () = { print($0) }
Then you can call it as you wish:
doSomethingTwo(closure: closure)