0

I'm trying to implement a custom class extending UIControl in swift and can't quite work out the initialisation.

class UIRangeSlider: UIControl {
    var minimumValue: Float32
    var maximumValue: Float32

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

    init(frame: CGRect, minimumValue: Float32, maximumValue: Float32) {
        self.minimumValue = minimumValue
        self.maximumValue = maximumValue
        super.init(frame: frame)
    }
}

When I try to create an instance of this class with:

var sliderFrame = CGRect(x: 20, y: 200, width: 200, height: 5)
var slider = UIRangeSlider(frame: sliderFrame, minimumValue: 1, maximumValue: 10)

I get the error:

Property 'self.minimumValue' not initialised at super.init call

What is the correct way to write this custom initialiser?

1
  • All non-optional properties must be initialized at compile time ;) Commented Nov 19, 2014 at 11:12

1 Answer 1

1

Swift always requires any new members of class to have some kind of default value before you can call designated init.

required init(coder aDecoder: NSCoder) {
    self.minimumValue = 0.0 // some default value
    self.maximumValue = 0.0 // some default value

    super.init(coder: aDecoder)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to alter the coder function to take more parameters? Or is there any other way to only allow initialisation with a given minimum and maximum value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.