How can we call class functions with a dynamic class name?
Assume the following example where I have two class with methods with same signature
class Foo{
class func doSomething()
}
class Foobar {
class func doSomething()
}
class ActualWork{
//call following method with a variable type so that it accepts dynamic class name
func callDynamicClassMethod(x: dynamicClass)
x.doSomething()
}
How can this be implemented so that x accepts values at run time
Edit: Sorry, I missed to mention that I was looking for any other ways other than protocol oriented approach. This is more of an exploratory question to explore if there is a more direct approach/pods/libraries to achieve this.
I liked this question, because it made me to think a lit'bit outside of the box.
I'll answer it, by dividing it into a few parts.
First
Class function is basically a Type methods, which can be achieved using the
staticword inside theclasscontext.Taking that into account, you can get a simple solution, using protocol and passing the class reference (conforming to that protocol) like this:
Second
In case you don't really need the method on the class context, you may consider using instance methods. In that case the solution would be even simpler, like this:
Third
If you need to use the
class funcsyntax, as OP originally did:You CANNOT simply use a protocol. Because protocol is not a class... So compiler won't allow it.
But it's still possible, you can achieve that by using Selector with NSObject.perform method
like this: