Swift闭包变量捕获趣味题
2020-12-10 本文已影响0人
CoderXLL
题目一
var car = "大奔"
let block = { (car: String) in
print("我开\(car)")
}
car = "雅迪"
block(car)
block的参数是外界传入的,调用时block传入的参数值为"雅迪",所以答案为
我开雅迪
题目二
var car = "大奔"
let block = { [ car ] in
print("我开\(car)")
}
car = "雅迪"
block()
block在调用之前,将car捕获为自身局部变量,捕获时car的值为"大奔",所以答案为
我开大奔
题目三
var car = "大奔"
let block = {
print("我开\(car)")
}
car = "雅迪"
block()
block没有对car进行复制,所以block内部的car还是全局的car变量,所以答案为
我开雅迪
题目四
class Car {
var name: String = ""
}
var car = Car()
car.name = "大奔"
let block = { [ car ] in
print("我开\(car?.name)")
}
car.name = "雅迪"
block()
block在调用之前,将car捕获为自身的局部变量,但是car的name属性为指针类型,所以答案为
我开雅迪
题目五
在题目四的基础上,在name重新赋值前,更新car的指针指向,即
class Car {
var name: String = ""
}
var car = Car()
car.name = "大奔"
let block = { [ car ] in
print("我开\(car.name)")
}
car = Car()
car.name = "雅迪"
block()
block在调用之前,将car捕获为自身的局部变量,又因为car在block调用之前就被重新赋值,所以block捕获的car与外界的car不是同一个,block捕获的car还是car在第二次赋值前的那个,即name="大奔"。所以答案为
我开大奔
题目六
在题目五的基础上,捕获的car用weak修饰,即
class Car {
var name: String = ""
}
var car = Car()
car.name = "大奔"
let block = { [ weak car ] in
print("我开\(car?.name)")
}
car = Car()
car.name = "雅迪"
block()
如题五的解释的基础上,因为捕获的car为弱引用类型,所以此时car在block中相当于做了一次浅拷贝,在car被重新赋值时,原指针被销毁。所以答案为
我开nil