how to create instance of a class from a string in

2019-02-05 18:39发布

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 solutions I have tried that are not working

- Making class an objective-c class

@objc(customClass)
class customClass {
    ...
}

//Error here: cannot convert value of type 'AnyClass?' to expected argument type 'customClass'
let c: customClass = NSClassFromString("customClass")

- Specifying class using NSString value (both with and without using @objc attribute)

@objc(customClass)
class customClass {
    ...
}

//Error here: cannot convert value of type 'String' to expected argument type 'AnyClass' (aka 'AnyObject.Type')
var className = NSStringFromClass("customClass")

let c: customClass = NSClassFromString(className)

I'm not doing something right but have not found any solutions online.

How do I create an instance of a class using a string in Swift 3?

标签: swift swift3
3条回答
Root(大扎)
2楼-- · 2019-02-05 19:07

If you project contains space you should replace space with '_'

Something like this

let namespace = (Bundle.main.infoDictionary!["CFBundleExecutable"] as! String).replacingOccurrences(of: " ", with: "_")
let cls = NSClassFromString("\(namespace).\(className)")! as! AnyClass
查看更多
劳资没心,怎么记你
3楼-- · 2019-02-05 19:09

I have added my category to convert classes here: https://stackoverflow.com/a/45112622/182551

查看更多
做自己的国王
4楼-- · 2019-02-05 19:17

You can try this:

func stringClassFromString(_ 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 = stringClassFromString("customClass") as! UITableView.Type
let instance = myclass.init()
查看更多
登录 后发表回答