How to create an object based on a string in Swift?

Here is my code that I would like to reorganize:

let myCell = MyCustomTableViewCell()
self.createCell(myCell, reuseIdentifierString: "myCellIdentifier")

MyCustomTableViewCell conforms to the SetCell protocol, so it works great. and SetCell protocol is not @obj_c protocol. This is a quick protocol.

private func createCell<T where T:SetCell>(classType: T, reuseIdentifierString: String) -> UITableViewCell {
  var cell = _tableView.dequeueReusableCellWithIdentifier(reuseIdentifierString) as T
  cell.setText()
  return cell.getCustomCell()
}

And now I am reorganizing my code, I would like to create myCell depending on String, but the string is exactly the same as the name of my class. I do not want to use else-if or switch-case

let myCell: AnyClass! = NSClassFromString("MyCustomTableViewCell")
self.createCell(myCell, reuseIdentifierString: "myCellIdentifier")

But now myCell, which is AnyClass, is not protocol compliant. How can i do this?

+4
source share
2 answers

, . AnyClass, AnyObject. . :

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:MyCell = theObject as MyCell

, :

1. , . , UITableViewCell. :

protocol SetCell {
    func setcell() {}
}
class BaseUITableViewCell : UITableViewCell, SetCell {
    func setcell() {}
}
class MyCell : BaseUITableViewCell {
    override func setcell() {}
}

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:BaseUITableViewCell = theObject as BaseUITableViewCell

2. UITableViewCell , ,

extension UITableViewCell: SetCell {}

// :

Declarations from extensions cannot be overridden yet

//: , . , , ...

3. , , :

@objc protocol SetCell {
    func setcell() {}
}

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var myCell2:protocol<SetCell> = objectType() as protocol<SetCell>
+5
class IndexViewController: UIViewController{}

let className = "IndexViewController"

let bundlePath = NSBundle.mainBundle().bundlePath
let bundleFullName = bundlePath.componentsSeparatedByString("/").last
let bundleName = bundleFullName?.componentsSeparatedByString(".").first
let clazz = NSClassFromString(bundleName! + "." + className)! as! UIViewController.Type
let object = clazz.init()
// let object1 = Index() 
0

All Articles