以下函数会打印出什么?
var car = "Benz"
let closure = { [car] in
print("I drive \(car)")
}
car = "Tesla"
closure()
因为 clousre
已经申明将 car
复制进去了([car])
,此时clousre
里的 car
是个局部变量,不再与外面的 car
有关,所以会打印出"I drive Benz"。 此时面试官微微一笑,将题目略作修改如下:
var car = "Benz"
let closure = {
print("I drive \(car)")
}
car = "Tesla"
closure()
此时closure
没有申明复制拷贝car
,所以clousre
用的还是全局的car
变量,此时将会打印出 "I drive Tesla"