闭包练习篇
struct Closure_T {
static func autoClosure(closure: @autoclosure ()->String){
print(closure())
}
static func tailClosure(num:Int,closure:(Int)->String){
print("\(num) + \(closure(5))")
}
static func reternClosure() ->()->String{
//这里要求返回一个闭包,但是返回一个函数也没毛病,闭包的本质也是函数?
func aaa() -> String{
return "我是一个函数"
}
return aaa
}
}
看着方便,所以定义了一个结构体
class ViewController: UIViewController {
var result:myClosuer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//自动闭包可以传表达式,闭包中的代码块延迟执行
var arr = ["2","3","4","5"]
Closure_T.autoClosure(closure: arr.remove(at: 0))
// 逃逸闭包,在函数之外调用,延长代码的生命周期
let c:myClosuer = {
print("i m a escaping closure")
}
escapingClosure(closure: c)
result!()
//尾随闭包 ,闭包作为参数可以不用写在()中
Closure_T.tailClosure(num: 6) { (code:Int) -> String in
return "\(code)"
}
//闭包各种写法
//完整
let cl = { (str:String) -> String in
return str + "哈哈"
}
//省略类型,根据上下文判断自行推断类型
let cl2 = { str in
return str + "哈哈"
}
//单表达式可省略 return
let cl3 = { str in
str + "哈哈"
}
//简写->$0代表有参闭包中的第一个参数
let cl4 = {$0 + "哈哈"}
print(cl4("嘻嘻"))
//闭包捕获变量
//闭包变量捕获是在执行的时候确认变量的值(或者说闭包捕获了这个变量的引用或指针),如果想在变量创建的时候捕获其值,需要使用捕获列表,捕获变量的值而不是引用,使用[],书写style:[形参=实参] or [形参]
var a = 10
let clo = {[acopy = a] in
print(a)
print(acopy)
}
a = 20
clo()
let clos = Closure_T.reternClosure()
print(clos())
}
func escapingClosure(closure:@escaping myClosuer){
result = closure
}
}
注释都是个人浅薄的理解,欢迎大家指正
网友评论