简体   繁体   中英

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.

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. 在此处输入图片说明

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

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

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)

if you're getting this error you're probably missing an = sign

for eg

yourClosure = { variable: VariableType in 
    print(variable)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM