Now, in the last lesson, we created what's called a getter, 1
so a block of code that will execute whenever we try to get the value of a property. Now, computed properties 2
also allow you to specify some code that should be executed when its value is set 3
and this is called a setter. 4
So, for example, in addition to this block for "get." underneath it. I can also write a block that's called 5
"set," and the block of code inside the set will be executed whenever this property gets a new value set 6
to it. 7
So, for example, inside here, I can simply write a print statement that says "numberOfSlices 8
now has a new value which is," 9
and there's a special variable that we can tap into which is called newValue, and this new value is 10
equal to, essentially, exactly that, it's the newValue that's been given to numberOfSlices. 11
So, for example, if we delete all of this and we simply write numberOfSlices is equal to 12, then you 12
can see right away down here, we get printed numberOfSlices 13
now has a new value which is 12, and that new value comes from this line here. 14
So having this block of code, which we call the setter, allows us to tap into the exact moment when our property 15
is set with a new value, and it allows us to use that new value in computations or various bits of code, 16
and to execute it at the exact time when this property's value gets updated. 17
Now, if you don't have a setter specified for your computed property, say, if we delete that block, you can 18
see that you get an error here 19
when I try to set a numberOfSlices equal to 12, and it says that "Cannot assign to value: 'numberOfSlices' is 20
a get-only property." 21
So because I only have a block specified for "get," then this computed property is now effectively read-only, 22
so I cannot set it to have a new value, but I can use it whenever I need to. 23
So this still works.