简体   繁体   中英

Why can't I remove elements from an Array in its willSet event?

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.

The behavior has nothing to do with value type / reference type

Please note the warning

Attempting to store to property 'MyArr' within its own willSet, which is about to be overwritten by the new value

which means that modifying the object in willSet has no effect.

Citing the Language Guide - Properties - Property Observers [ emphasis mine]:

Property Observers

Property observers observe and respond to changes in a property's value.

...

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 .

As you are experimenting with the willSet property observer, any mutation of the property you are observing within the willSet block precedes the actual storing of the newValue which follows immediately after the willSet block. This means you are essentially attempting to mutate "the old copy" of myArr prior to it being replaced with its new value.

Arguably this could be discussed as something illegal, as any mutation of myArr should 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 the willSet case, 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]:

Querying and Setting Type Properties

...

The currentLevel property has a didSet property observer to check the value of currentLevel whenever it is set. ...

NOTE

In the first of these two checks, the didSet observer sets currentLevel to a different value. This does not, however, cause the observer to be called again.

This is also a special case we can somewhat expect, as eg didSet is an excellent place to incorporate eg bounds checks that clamps a given property value to some bounds; ie, 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:

var myArr = [String]() {
    didSet {
        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 content is \(myArr)") // The content is ["too much."]

aAlan's comment on didSet vs willSet is interesting. I tried the same code but with didSet and it did remove the elements from the array which seemed odd initially. I think it's by design. My reasoning is:

  • if you actually did get a reference to the actual item itself inside willSet and made changes then everything would get overwritten. It makes all your changes nullified. Because you're doing this before you even read what's about to happen. Also (repeating what dfri has said) if you set it again inside willSet well then you're going to trigger the property observer again and again and will create a feedback loop which will crash the compiler, hence the compiler behind the scene creates a copy avoiding all this... will just suppress this mutation ie it won't allow it. It won't create a copy...simply put it would just ignore it. It does that by throwing a vague (because it doesn't really tell you that it will ignore the changes) warning:

在此处输入图片说明

  • same is not true with didSet . You wait...read the value and then make your decision. The value of the property is known to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM