Search code examples
iosswiftstaticstatic-methodsswift5

How to run code when a static instance is initialized?


I'm using this pattern:

open class CoreDataHub {

public static let sharedInstance = CoreDataHub()
  open class func getThing() -> String {
    return "hello world"
  }
  init() {
    sharedInstance.getThing()
  }

}

But I get the following error:

Static member 'getThing' cannot be used on instance of type 'CoreDataHub'

My goal is to run some code...namely call getThing() when the sharedInstance is initialized. Any ideas? Thank you


Solution

  • You are getting

    Static member 'getThing' cannot be used on instance of type 'CoreDataHub'
    

    because, you are called getThing() static method using sharedInstance object.

    Use CoreDataHub.getThing() instead of sharedInstance.getThing()

    public static let sharedInstance = CoreDataHub()
    init() {
        let value = CoreDataHub.getThing()
        
    }