Loadex
Loadex

Reputation: 1512

Swift nsobjectype constructor

I'm trying to create a widget manager in swift, and to crete the widget i've decided to use dynamic type an instanciate my widget according to the name of the widget class. All my widgets inherit from the abstractUIWidget type. Yep with this code I cannot manage to build my call.

    var anyobjectype : AnyObject.Type = NSClassFromString(widgetType)
    var nsobjectype : AbstractUIWidget.Type = anyobjectype as AbstractUIWidget.Type
    var rec: AbstractUIWidget = nsobjectype(frame:CGRectMake(0, 0, 0, 0))

I get an error on the following line.

    var rec: AbstractUIWidget = nsobjectype(frame:CGRectMake(0, 0, 0, 0))

Constructing an object of class type 'AbstractUIWidget' with a metatype value must have a 'required' initializer.

But yet in my AbstractUIWidget class I have the following methods :

override init(frame: CGRect) {
    super.init(frame: frame)
}

required override init() {
    super.init()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

Did i miss anything ? Thanks for your help !

Upvotes: 4

Views: 1814

Answers (1)

Antonio
Antonio

Reputation: 72790

You have to make this initializer required:

override init(frame: CGRect) {
    super.init(frame: frame)
}

Tested with this code in a playground and it works:

class AbstractUIWidget : UIView {
    required override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required override init() {
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

class ConcreteUIWidget : AbstractUIWidget {       
}

var widgetType = ConcreteUIWidget.description()

var anyobjectype : AnyObject.Type = NSClassFromString(widgetType)
var nsobjectype : AbstractUIWidget.Type = anyobjectype as AbstractUIWidget.Type
var rec: AbstractUIWidget = nsobjectype(frame:CGRectMake(0, 0, 0, 0))

Upvotes: 5

Related Questions