0

I am getting Property self.color not initialized as super.init call error with the below code. How can I properly override the init(frame:) function please? I'd like to pass the color along with the init call.

class CircleView: UIView {

    // properties
    let color: UIColor

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

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

    override func drawRect(rect: CGRect) {
        ...
    }
}
Martin Koles
  • 5,177
  • 8
  • 39
  • 59
  • Check out http://stackoverflow.com/questions/24021093/error-in-swift-class-property-not-initialized-at-super-init-call Also, might need to try var instead of let. Also could set a default value for color. – shim Dec 04 '14 at 18:09
  • 1
    change `let color: UIColor` to `var color: UIColor!` – bbarnhart Dec 04 '14 at 18:12
  • Both of these tips work. I am taking @bbarnhart. Thank you. Happy to accept as answer.. – Martin Koles Dec 04 '14 at 18:14
  • I believe the `init(frame:)` method is fine. The error should be in the `init(coder:)` method. Here you call `super.init` before initializing your `color` property. – Jack Dec 04 '14 at 18:52

1 Answers1

2

Note that any property declared as "let" must be initialized during all possible inits. You are not doing it when the deserialization init is invoked. Thats why it does not compile.

Now that you understand the reason, let's go for the solution. You can make your constant an optional variable, so it does not need to be initialized, which should solve the problem but add another problem: now it is mutable.

If you still want to keep a let (and you probably want, otherwise you would have already defined a var), you need to decode the content from the coder that the second init receives. While doing that you must also override the serialization process and write the color value so your uiview can be properly serialized.

If you are not caring at all about serialization, the first option solves your problem. If you care about what's happening to your code, I suggest going for understanding the serialization API in Swift and implementing the proper init(decoder) and encoder method.

  • Good point. From "The Swift Programming Language": "You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes." – Maciej Kozieł Dec 04 '14 at 18:33