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];
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With