Using protocol functions at unknown class

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)

Answered by OOPer in 697563022

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"))
}

What do you want to achieve? For almost all the code using NSClassFromString, there would be more Swifty and better ways.

OOPer. I have a lot of classes (let's name them data processors). User may select one, and I need to save this selection and later use an instance of this class. Now I'm saving the class name as NSStringFromClass. Thanks, I will be grateful for ideas.

How many classes? Thousands or more?

Much less, about 50. Maybe just make a function that will give the instance from name? Like this https://gist.github.com/Higher08/d54e07ac752884a5e615f15bc7e73ba0

Accepted Answer

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"))
}
Using protocol functions at unknown class
 
 
Q