Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Get current class from a static method

Tags:

static

swift

self

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?

like image 863
Nathan H Avatar asked Feb 03 '16 11:02

Nathan H


1 Answers

self works in static methods too, like this:

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

  static func doIt() {
    self.prepare();
  }
}
like image 113
RobbeR Avatar answered Nov 15 '22 12:11

RobbeR