The logic is to clear an Array when it has a specified amount of elements. I could put the check outside of the Array but I was trying to see what if do it in Array's willSet event. The result is elements in Array stay still.
Here is the code
var MyArr=[String]() {
willSet{
print("now count is:\(MyArr.count)")
if MyArr.count>2 {
print("now remove all!")
MyArr.removeAll()
}
}
}
MyArr.append("hello")
MyArr.append(",world")
MyArr.append("!")
MyArr.append("too much.")
print("The conent is \(MyArr)")
MyArr was expected to have only one elements while actual result was four.

Citing the Language Guide - Properties - Property Observers [emphasis mine]:
As you are experimenting with the
willSetproperty observer, any mutation of the property you are observing within thewillSetblock precedes the actual storing of thenewValuewhich follows immediately after thewillSetblock. This means you are essentially attempting to mutate "the old copy" ofmyArrprior to it being replaced with its new value.Arguably this could be discussed as something illegal, as any mutation of
myArrshould lead to the invocation of any property observers, thus mutation of a property within a property observer (mutation of the reference for reference types or the value for value types) could arguably lead to recursive calls to the property observer. This is not the case, however, and for thewillSetcase, specifically, instead a warning is emitted, as pointed out in @vadian's answer. The fact that mutation of the property itself within a property observer will not trigger property observers is not really well-documented, but an example in the Language Guide - Properties - Type Properties points it out [emphasis mine]:This is also a special case we can somewhat expect, as e.g.
didSetis an excellent place to incorporate e.g. bounds checks that clamps a given property value to some bounds; i.e., over-writing the new value by a bounded one in case the former is out of bounds.Now, if you change to mutate the property to after the new value has been stored, the mutation will take affect and, as covered above, not trigger any additional calls to the property observers. Applied to your example: