I'm using NSClassFromString
to create a class type. But I do not have the type as ClassName.Type,
only as a string. Although, I'm sure this class will be with SourceProtocol. And I want to call functions of this protocol. How can I do it?
I tried casting to this protocol. But protocol doesn't have inits. Therefore I can't use functions.
And here's example
import Cocoa
protocol NeededMethods {
func doSmt(str: String) -> String
}
struct FirstImplementation: NeededMethods {
func doSmt(str: String) -> String {
str.replacingOccurrences(of: "1", with: "0")
}
}
let anyclass = NSClassFromString("FirstImplementation")
I want to call doSmt
, without using FirstImplementation.Type
(because it can be any class, not only FirstImplementatioon)
Maybe just make a function that will give the instance from name?
I would use a Dictionary
, if the number is 50 or so.
let stringToNeededMethods: [String: NeededMethods] = [
"FirstImplementation": FirstImplementation(),
//...
]
if let theInstance = stringToNeededMethods["FirstImplementation"] {
print(theInstance.doSmt(str: "0123"))
}