Search code examples
swiftlifecycle

Swift does the "get" method will change the value of variable?


I just want to do something when the variable update value, and do not change the value. But the "get" is required if I implement "set", so I try to return the value self. It looks has already in "hell cycle":

var imageInfo:ImageInfo! {

    get {
        return self.imageInfo
    }
    set(info) {
        self.imageView.image = UIImage(named: info.fileName)
    }

}

Solution

  • If you want to do something when update the value, you should implement didSet method.

    var imageInfo:ImageInfo! {
    
            didSet{
             // do your stuff here
             self.imageView.image = UIImage(named: imageInfo.fileName)
            }
    
    }