Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 783
Danoram Avatar asked Nov 02 '16 05:11

Danoram


People also ask

How do you use NSClassFromString?

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.

What is instances in Swift?

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.


2 Answers

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() 
like image 68
Nick xu Avatar answered Oct 08 '22 02:10

Nick xu


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

like image 33
Daniel Storm Avatar answered Oct 08 '22 01:10

Daniel Storm