How to create an instance of a class from a String in Swift

Apple provides a way to achieve this without having to use NSClassFromString.

Bundle.main.classNamed("MyClassName")

https://developer.apple.com/documentation/foundation/bundle/1407299-classnamed


You can try this:

func classFromString(_ className: String) -> AnyClass! {

    /// get namespace
    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String

    /// get 'anyClass' with classname and namespace 
    let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!

    // return AnyClass!
    return cls
}

use the func like this:

class customClass: UITableView {}   

let myclass = classFromString("customClass") as! UITableView.Type
let instance = myclass.init()

Tags:

Swift