swift 属性观察器(Property Observer)

122 阅读1分钟

1、 使用lazy可以定义一个延迟存储属性,在第一次用到属性的时候才会进行初始化

class PhotoView {
  lazy var image: Image = {
    let url = "https://www.520it.com/xx.png"
    let data = Data(url: url)
    return Image(data: data)
  }()
}

2、lazy属性必须是var,不能是let
3、必须在实例的初始化方法完成之前就拥有值 如果多条线程同时第一次访问lazy无法保证属性只被初始化1次(线程不安全)

4、可以为非lazy的var存储属性设置属性观察器

struct Circle {
  var radius: Double {
    willSet {
      print("willSet", newValue)
    }
    didSet {
      print("didSet", oldValue, radius) 
    } 
  }
  init() {
  	self.radius = 1.0
  	print("Circle init!") 
  }
}
  • willSet会传递新值,默认叫newValue
  • didSet会传递旧值,默认叫oldValue
  • didSet会传递旧值,默认叫oldValue
  • 在属性定义时设置初始值也不会触发willSet和didSet