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

前端 未结 4 1354
终归单人心
终归单人心 2020-12-08 19:47

I have tried creating an instance of a class using a string in numerous ways with none of them working in Swift 3.

Below are pre-Swift 3 sol

4条回答
  •  萌比男神i
    2020-12-08 20:13

    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()
    

提交回复
热议问题