defer:defer中的代码将延迟至当前作用域结束之前执行
注意:必须有执行到defer,才会触发defer。如果提前return、抛异常或通过判断过滤了导致没有走defer这一行,就不会触发。
var a = 0
func test() {
a = 0
defer{
a = 1
}
a = 2
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
test()
print("a =",a)
}
test()执行顺序为:a=0 -> a=2 -> a=1
所以打印:a = 1
常见使用场景:
1、do-catch
func Person() {
defer {
print("study")
}
do {
throw err.msg("123")
print("eat")
} catch {
print("run")
}
}
func Person() {
defer {
print("study")
}
do {
throw err.msg("123")
print("eat")
} catch {
print("run")
}
}
Person()调用顺序:先执行do catch代码块,,再执行defer
打印结果:
run
study
2、多个defer,执行顺序与定义顺序相反
func fn1() {
print("fn1")
}
func fn2() {
print("fn2")
}
func fn3() {
print("fn3")
}
//执行顺序与定义顺序相反
func test() {
defer {fn1()}
defer {fn2()}
defer {fn3()}
}
test()
打印结果:
fn3
fn2
fn1
网友评论