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

What is the use of observer property didSet and willSet in Swift language?

I am new to swift language .The swift offers new object oriented feature property observer "willSet" and "didSet".How it is different from common objective C property .


The main usage is to capture and escalate the old and new values of the variable. willSet captures the newValue to which the property, variable, is about to be set and didSet captures the oldValue.

They're extremely handy for setup and teardowns... e.g.

var fileHandle: FileHandle {
        otherClass.disableAccessTo(handle: newValue)
        otherClass.enableAccessTo(handle: self.fileHandle)
        yetAnotherClass.archiveFile(handle: oldValue)