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?
You can use NSClassFromString to get a variable of type AnyClass but there appears to be no way in Swift to instantiate it. You can use a bridge to Objective C and do it there or -- if it works in your case -- fall back to using a switch statement.
Swift Objects An object is called an instance of a class. For example, suppose Bike is a class then we can create objects like bike1 , bike2 , etc from the class.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With