Why does didSet observer fire for property of type Set after calling insert with value already in the set?

Consider the following snippet from my Xcode Playground:

import UIKit

var collection = Set<String>() {
    didSet {
        print("didSet")
    }
}

collection.insert("Test1")
collection.insert("Test2")
collection.insert("Test1")
collection.insert("Test3")

print("Done")

Why is the output:

didSet
didSet
didSet
didSet
Done

instead of:

didSet
didSet
didSet
Done

Why does it fire when the set isn't changed, since the value is already in the set?

1 Like

Every mutating func will act like this.

There's no special mechanism by which the property knows that the Set wasn't modified internally.

4 Likes

Got it, makes sense. Thanks!