Search code examples
arraysswiftobserversdidset

Why Swift Array cannot be altered in property observer didSet?


It seems that Swift's Array won't go through didSet, why?

var intArray: [Int] = [] {
    didSet {
        intArray += [0]
    }
}

if intArray.count == 0 {
    println("Why is intArray not being altered?")
}

Solution

  • willSet and didSet are not invoked when a variable is first initialized, so that's normal behavior, and valid for all property types - being an array makes no difference.

    Try this in a playground:

    var intArray: [Int] = [] {
        didSet {
            intArray += [0]
        }
    }
    
    intArray = []
    
    intArray
    

    the last statement shows that intArray is [0].

    Read the 2nd note in Property Observers