Create instance of class known at runtime in Swift

后端 未结 3 1209
遇见更好的自我
遇见更好的自我 2021-02-14 14:00

A picture is worth a thousand words, how to rewrite this code from Objective-C to Swift?

- (id) instanceOfClass: (Class) class withInitializer: (SEL) initializer         


        
3条回答
  •  不知归路
    2021-02-14 14:25

    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.

提交回复
热议问题