Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class of instance and call class function in Swift 4?

Tags:

swift

In Objective-C, it was simple to get the class of an instance and call class methods on it. How do you do this in Swift 4?

e.g.

MyObject * obj = [[MyObject alloc] init];
[[obj class] someClassMethod];
like image 482
R OMS Avatar asked Oct 16 '17 17:10

R OMS


People also ask

How do you call a class method?

A class method is a method that's shared among all objects. To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method.


1 Answers

You can use the type(of) method to get the class of an object, and use this to call a class method on it.

class MyObject {
  static func someClassMethod() {

  }
}
let obj = MyObject()
type(of: obj).someClassMethod()
like image 109
Craig Grummitt Avatar answered Oct 23 '22 07:10

Craig Grummitt