Search code examples
swiftsingleton

Why is Code in Initializer of Singleton not executed on App Launch?


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?

Solution

  • 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