Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

didSet vs willSet? [duplicate]

Tags:

ios

swift

I'm very new at programming and I'm having trouble understanding these two property observers.

I'm currently building an app with a table view where date pickers are contained in the rows of it. In this case I have two date pickers. As you all know, date pickers take a big amount of height in cells, therefore you need to hide them. The following code takes care of it:

var isCheckInDatePickerShown: Bool = false {
    didSet{
        checkInDatePicker.isHidden = !isCheckInDatePickerShown
    }
}

var isCheckOutDatePickerShown: Bool = false {
    didSet{
        checkOutDatePicker.isHidden = !isCheckOutDatePickerShown
    }
}

I have a very basic knowledge of programming so I'm confused by the functionality of didSet. What would happen with a willSet?


1 Answers

As Apple describes it:

You have the option to define either or both of these observers on a property:

willSet is called just before the value is stored.

didSet is called immediately after the new value is stored.

So basically code performed in willSet will not have access to the newValue of the variable while it runs, whereas didSet will have access to it (since it's "after it's been set").

For :

var isCheckInDatePickerShown: Bool = false {
    willSet{
        print("This new value is: \(isCheckInDatePickerShown)")
    }
}
var isCheckOutDatePickerShown: Bool = false {
    didSet{
        print("This new value after it was set is: \(isCheckOutDatePickerShown)")
    }
}

if you call them:

print(isCheckInDatePickerShown)
.isCheckInDatePickerShown = true
print(isCheckInDatePickerShown)

Will print:

false

"This new value is: false"

true

print(isCheckOutDatePickerShown)
.isCheckOutDatePickerShown = true
print(isCheckOutDatePickerShown)

Will print:

false

"This new value after it was set is: true"

true

As you can see, the code ran in willSet did not yet have access to the new value, because it has yet to be committed to memory. Whereas didSet did have access to it.

like image 178
jlmurph Avatar answered Nov 03 '25 21:11

jlmurph