- The simplest way to write closures, here is the format
{(parameters) -> return type in statements }
Examples
//let append = {(str1 aa:String ,Str2 bb: String)-> String in error, the closure has no external parameter name let append = {(str1:String,Str2: String)-> String in print("\(str1)------\(Str2)")//20------30 return "\(str1)\(Str2)"//2030 } //print(append(str1:"20",str2:"30")) error, no need to pass parameter names in the closure print(append("20","30"))//2030
The above is equivalent to
let append: (String, String) -> String = { (str1, str2) in return str1 + str2 } print(append("one", "two"))//onetwo
- If there are no parameters but a return value, you can write like this
< pre class="brush:csharp;gutter:true;">//If there is no parameter, you can just omit “in”. If you add in, an error will be reported here
let test: () -> String = {
return “test closure”
}
print(test())//test closure
let test: () -> String = {
return “test closure”
}
print(test())//test closure
- No parameter, no return value
let test: () -> Void = { print("test closure")//output: test closure } test()
- There can be no parameters in the closure, but there is no return value, otherwise an error will be reported
let test: (String) -> void = {//An error is reported here
(str1) in print(str1)
}
- Delay of closure
func showYouTest(testBlock: @escaping () -> Void) { //Do a delayed operation DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { //Call the closure after five seconds testBlock() } print("I am a function") } showYouTest { print("11111111111111111111")//5 seconds later execute here }
{(parameters) -> return type in statements }
//let append = {(str1 aa:String,Str2 bb: String)-> String in error, closed Package has no external parameter name let append = {(str1:String,Str2: String)-> String in print("\(str1)------\(Str2)")//20------30 return "\(str1)\(Str2)"//2030 } //print(append(str1:"20",str2:"30")) error, no need to pass parameter names in the closure print(append("20","30"))//2030
let append: (String, String) -> String = { (str1, str2) in return str1 + str2 } print(append("one", "two"))//onetwo
//If there is no parameter, you can just omit "in". If you add in, an error will be reported here let test: () -> String = { return "test closure" } print(test())//test closure
let test: () -> Void = { print("test closure")//output: test closure } test()
let test: (String) -> void = {//An error is reported here
(str1) in print(str1)
}
func showYouTest(testBlock: @escaping () -> Void) { //Do a delayed operation DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { //Call the closure after five seconds testBlock() } print("I am a function") } showYouTest { print("11111111111111111111")//5 seconds later execute here }