0

Context

I have a Singleton which should perform some setup logic inside its private initializer. However, this code does not get executed on app launch.


Code

class SomeViewModel: ObservableObject {
    static let shared = SomeViewModel()

    private init() {
        fatalError() // Just to test whether the Code gets executed.
    }
}

Question

  • The app does not crash with a Fatal Error even this should happen when the initializer gets executed. Why does this happen?
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
christophriepe
  • 1,157
  • 12
  • 47

1 Answers1

1

The static let is lazy. It won't be initialized until the first call to access the shared property. So your app won't crash until you do:

let x = SomeViewModel.shared
HangarRash
  • 7,314
  • 5
  • 5
  • 32