Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using closures as parameters without trailing closures Swift

Tags:

ios

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.

like image 856
WishIHadThreeGuns Avatar asked Nov 07 '22 20:11

WishIHadThreeGuns


1 Answers

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)
like image 183
Leo Dabus Avatar answered Nov 14 '22 21:11

Leo Dabus