- 闭包最最简单的写法 ,一下是格式
{(parameters) -> return type in statements }
举例
//let append = {(str1 aa:String,Str2 bb: String)-> String in 报错,闭包没有外部参数名 let append = {(str1:String,Str2: String)-> String in print("(str1)------(Str2)")//20------30 return "(str1)(Str2)"//2030 } //print(append(str1:"20",str2:"30")) 报错,闭包里面不用传参数名 print(append("20","30"))//2030
以上等价于
let append: ( String, String) -> String = { (str1, str2) in return str1 + str2 } print(append("one", "two"))//onetwo
- 如果如果无参数但是有返回值,可以这么写
//无参有反 可以直接省略 "in" 如果加上in,这里会报错 let test: () -> String = { return "test闭包" } print(test())//test闭包
- 无参无返回值
let test: () -> Void = { print("test闭包")//输出:test闭包 } test()
- 闭包里面不能有参数,但是无返回值,不然报错
let test: (String) -> void = {//这里报错 (str1) in print(str1) }
- 闭包的延迟
func showYouTest(testBlock: @escaping () -> Void) { //做一个延迟操作 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { //五秒之后调用闭包 testBlock() } print("我是函数") } showYouTest { print("11111111111111111111")//5秒后执行这里 }
- 把闭包当成一个参数传递
typealias comple = (String)->Void func aaa(result:comple){ result("好人一生平安") } print(aaa(result: { (String) in print("(String)")//输出:好人一生平安 }))
- 给一个数据,把数组的每一个元素+1
let arr = [1,2,3,4,5,6,7] func addOne(n1: Int) ->Int{ return n1+1; } let arr1 = arr.map(addOne) print(arr1)//[2, 3, 4, 5, 6, 7, 8]
等价于
let arr = [1,2,3,4,5,6,7] let arr1 = arr.map{(n1) in n1+1} print(arr1) //[2, 3, 4, 5, 6, 7, 8]
等价于
let arr = [1,2,3,4,5,6,7] let arr1 = arr.map{$0+1} print(arr1) //[2, 3, 4, 5, 6, 7, 8]