swiftstaticself

Swift: Get current class from a static method


In Swift, let's say I want to add a static factory method that returns an instance:

class MyClass {
  static func getInstance() {
    return MyClass(someProperty);
  }
}

But what if I don't want to write the class name? Is there an equivalent of self but for static methods and properties?

Same idea if I want to call another static method from a static method:

class MyClass {
  static func prepare(){
    //Something
  }

  static func doIt() {
    MyClass.prepare();
  }
}

Can I do this without using MyClass explicitly?


Solution

  • self works in static methods too, like this:

    class MyClass {
      static func prepare(){
        print("Hello");
      }
    
      static func doIt() {
        self.prepare();
      }
    }