5

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?")
}
Max MacLeod
  • 26,115
  • 13
  • 104
  • 132
Bruce You
  • 167
  • 1
  • 9

1 Answers1

5

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

Antonio
  • 71,651
  • 11
  • 148
  • 165
  • 1
    Ok but what if I want to sort that array whenever it is updated? I tried in `didSet` but it crashes!! Any suggestion please? – iRiziya Dec 02 '19 at 16:58