Skip to content →

Tag: Structures

Property Value Observing of Struct Types

The Swift Programming Language Guide has this to say about property value observing:

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.

Given that, how many times would you expect the following snippet to produce an output, “didSet dict”?

class SomeClass {
  var dict: [String: String]? {
    didSet {
      print("didSet dict")
    }
  }
}
let myClass = SomeClass()
myClass.dict = [:]
myClass.dict?["A"] = "alpha"
myClass.dict?.removeValueForKey("A")

What the documentation does not make clear is that for structures, which are value types, property observers are triggered both on assignment and on mutation; for classes, which are reference types, they are only triggered on assignment.

So for this example, where dict is a structure, didSet is called three times: once for the initial assignment, and twice for the two mutations. Good to know!

Leave a Comment