Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report

0

This is how you call a function

doSomethingTwo()

If we follow the pattern, put () first, then comes with its parameter, you'll get something like this.

doSomethingTwo(closure: { (str) in
     print(str)
})

By the way, Xcode will helps you to complete. But if you don't want its help, when you have this, don't tap, type the rest by your own. enter image description here

over 4 years ago · Santiago Trujillo Report

0

You're not calling the function correctly. You should call it like this:

doSomethingTwo(closure: { (text) in
print(text)
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!