11

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];
Hamish
  • 78,605
  • 19
  • 187
  • 280
R OMS
  • 652
  • 2
  • 7
  • 19
  • Possible duplicate of [Calling Type Methods Within An Instance Method](https://stackoverflow.com/questions/24472399/calling-type-methods-within-an-instance-method) – Cristik Oct 16 '17 at 19:13

1 Answers1

20

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()
Craig Grummitt
  • 2,945
  • 1
  • 22
  • 34