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?
If you project contains space you should replace space with '_'
Something like this
I have added my category to convert classes here: https://stackoverflow.com/a/45112622/182551
You can try this:
use the func like this: