Swift 闭包的值捕获

2021-10-18  本文已影响0人  sampson0115
以下函数会打印出什么?
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

上一篇下一篇

猜你喜欢

热点阅读