Search code examples
iosswiftdidset

swift ios why use didSet in this example


I am trying to understand why didSet it used in this example. Its a piece from a pagecontroller that displays images (image slider)

Code:

import UIKit

class PageItemController: UIViewController {

    // MARK: - Variables
    var itemIndex: Int = 0
    var imageName: String = "" {

        didSet {

            if let imageView = contentImageView {
                imageView.image = UIImage(named: imageName)
            }

        }
    }

    @IBOutlet var contentImageView: UIImageView?

    // MARK: - View Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        print(imageName)
        contentImageView!.image = UIImage(named: imageName)

    }
}

I have tried the same code but wihtout the didSet and I dont notice any changes in speed etc, so why is it used?


Solution

  • Actually didSet will set the uiimage with imageName string if imageName is set. If you are assigning imageName from anyother view then, You should use the code like :

    override func viewDidLoad() {
            super.viewDidLoad()
        }