Create instance of class known at runtime in Swift

╄→гoц情女王★ 提交于 2019-12-03 12:05:51

This cannot be done purely in Swift. You can only do this by creating the "class instance by name creator" in Objective C and calling this code from Swift.

For more information you can read this article. http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/

And check out this github repo https://github.com/ijoshsmith/swift-factory

If you can make your classes subclasses of a common superclass you can do this:

class C {
  var typ:String
  init() {
    self.typ = "C"
  }
  class func newInst() -> C {
    return C()
  }
}

class C1 : C {
  override init() {
    super.init()
    self.typ = "C1"
  }
  override class func newInst() -> C1 {
    return C1()
  }
}

class C2 : C {
  override init() {
    super.init()
    self.typ = "C2"
  }
  override class func newInst() -> C2 {
    return C2()
  }
}

var CL:C.Type = C1.self
CL = C2.self
var inst = CL.newInst()

inst.typ

If not then you can use a closure or block to create the instance and place those in a dictionary by name.

qwerty_so

See matt's excellent answer here. Basically with @objc you can mimic the dynamic creation of instances.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!