Website Links

Tuesday 5 May 2015

Swift Constructors

If you are interested in creating your own subclass of one of Swift's built in objects, you may often want to pass in additional arguments to the constructor. However, it isn't immediately obvious how to do this. The following code shows you how:

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

    convenience init(color: UIColor, bounds: CGRect) {
        self.init(frame: bounds)
        self.color = color
    }


    // will give you an error if you try to compile without this
    // after adding the above constructors
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }



To explain this a bit further, when you implement a custom constructor you will get an error if you don't implement the required constructor. The constructor you define must be prefixed with convenience and should make a call to the parent class constructor. However, you cannot make the call to the parent class constructor directly from your convenience constructor. The first constructor overrides and then calls the parent constructor so that you can make a call to it.

No comments:

Post a Comment