[Solved] How to let a value autofix itself when didSet?

The following snippet returns that the value is not autofixed from -1 to 0.
What should I do to let the autofix work?

import Foundation
class heck {
  private(set) var markerIndex: Int { didSet { if oldValue < 0 {
    markerIndex = 0
    print("attempted to fix")
  } } }
  init() {
    markerIndex = -1
  }
  public func newPrint() {
    print(markerIndex)
  }
}

let hi = heck()
hi.newPrint()

I found the issue. The "oldValue < 0" should be replaced to "markerIndex < 0".
Also, didSet won't work on init.

Correct, didSet won't be called if the variable is set from init directly:

init() {
    markerIndex = -1 // didSet won't be called
    markerIndex = -1 // didSet still won't be called
    { markerIndex = -1 }() // didSet will be called
    foo() // didSet will be called inside
}
func foo() {
    markerIndex = -1
}
2 Likes