Mr Dipuna Mr Dipuna - 1 month ago 7x
Swift Question

What is the use of Property Observer in Swift language?

I am new to swift language .The swift offers new object oriented feature property observer "willSet" & "didSet".So what is real time use of this properties in swift environment .


I use property observers and more specific didSetfor various things.

One example could be in a UIViewController where you have a UITableView and an array that holds the elements you'd like populate your table view from:

var persons: [Person]? = nil

now, every time you change something in your persons array, you'd like the table view to reload.

var persons: [Person]? = nil {
    didSet {

Another example could be @IBOutlets, if you'd like to set text color, font, background color and so on. Normally you'd do this in viewDidLoad() or some place like that, but now you can to that in didSet too, like so:

    @IBOutlet weak var headerLabel: UILabel! {
        didSet {
            headerLabel.font = UIFont.systemFontOfSize(15)
            headerLabel.textColor = UIColor.blueColor()
            headerLabel.text = NSLocalizedString("logIn", comment: "")

Now, when your headerLabel is initialized, these properties are set.

Hope that gives you an idea about how to use property observers :)