Swift requires all parameters to be set by the time the initialiser completes. It also requires these parameters to be set before calling another function, which is why the super initialiser is called afterwards, rather than in the first line as required by Objective-C.
In the normal initialiser, you are setting the value of data
to the passed in array. But you aren't doing so for the init(coder:)
method.
There are two ways to handle this:
One way is to just throw an assertion if the init(coder:)
initialiser is called.
required init?(coder decoder: NSCoder) {
fatalError("Not meant to be initialised this way")
}
The other is to assign a "empty" value:
required init?(coder decoder: NSCoder) {
data = [CGFloat]() // just set an empty array
super.init(nibName: "Test", bundle: nil)
}
The method you choose depends on how you want to use the code in your domain. I mostly choose the first option, because calling an initialiser that isn't meant to be used is a developer error, and it is a good idea to just crash for those types of error.