import Foundation//闭包:闭包的本质就是匿名函数(没有名字的函数,就是一个能完成特定功能的代码块//求和的函数func sum(num1:Int, num2:Int) -> Int{ return num1 + num2}/* (Int, Int) -> (Int) */let biBao:((Int, Int) -> (Int))biBao = { (num1:Int,num2:Int)->(Int) in return num1 + num2}//调用闭包let result = biBao(1,2)print(result)//无参数无返回值的闭包//func sayHello()->Void{// print("hello")//}//()->(Void) 无参数无返回值的闭包的闭包类型let b1:(()->(Void)) = { ()->(Void) in print("无参数无返回值的闭包类型") return print("提前结束函数")//提前结束一个函数 //print("123455")}b1()//无参数有返回值的闭包类型//func buyRedWiner() -> (Int) {// return 1//}//() -> (Int)let b2:(() -> (Int)) = { ()->(Int) in return 10}print(b2())//有参数有返回值var b3:((Int,Int)->(Int)) = { (n:Int, m:Int)->(Int) in return n + m}print(b3(1,5))b3 = { (a:Int, b:Int)->(Int) in return a - b}print(b3(10,5))//b3求两个数积的代码块b3 = { (a:Int, b:Int)->(Int) in return a * b}print(b3(3, 5))//闭包类型的变量,不止能存储一个代码块,而是能存储和变量类型一致的所有代码块//有参数无返回值的闭包//比较两个数的最大值并把最大值输出的闭包//(Int,Int)->(Void)let b4:((Int,Int)->(Void)) = { (num1:Int,num2:Int)->(Void) in print (num1 > num2 ? num1 : num2)}b4(10,12)//排序var arr = ["zhangsan","lisi","yifeng","xiaobai","xiaofan"]//可变的数组两种排序方式都能使用,不可变的只能使用sorted方法//升//arr.sort()//print(arr)arr.sort{(str1:String,str2:String)->Bool in //比较条件大于,得出的结果是降序 //比较条件小于,得出结果是升序 return str1 > str2}print(arr)//泛型(了解)func printContent(something:T){
print(something)
}
printContent(something: "123456")
printContent(something: 1)
printContent(something: 1.22)
网友评论