Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

140
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.

8 months 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)
8 months 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

8 months ago · Santiago Trujillo Report

0

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

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

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.