I just had the same problem .
As GoZoner said, marking your variables as optional will work. This is not a very elegant way, because you need to expand the value every time you want to access it.
I will write a request for improvement with Apple, perhaps we could get something like the "beforeInit" method, which is called before each init, where we can assign variables, so we do not need to use optional vars.
Until then, I just put all the assignments in the commonInit method, which is called from the allocated initializers. For example:.
class GradientView: UIView { var gradientLayer: CAGradientLayer?
Thanks to David, I looked again at the book, and I found something that could be useful for our deduplication efforts without using the optional variable hack. You can use closure to initialize a variable.
Setting default property value with closing or function
If the default value for stored properties requires some customization or customization, you can use the close function or the global function to provide a custom default value for this property. Whenever a new instance of the type to which the property belongs is initialized, either the function is closed and its return value is assigned as the default value of the property. These types of closures or functions usually create a temporary value of the same type as the property, spoil this value to represent the desired initial state, and then return this temporary value, which will be used as the default value of the property.
Here is a skeleton diagram of how you can use closure to provide a default property value:
class SomeClass { let someProperty: SomeType = {
Note that closing closes with a curly brace followed by an empty pair of brackets. This means that Swift will immediately close. If you omit these parentheses, you are trying to assign this property to the closure, not the return value of the closure.
Note
If you use closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point at which closure is performed. This means that you cannot access any other property values ββfrom your closure, even if these properties have default values. You also cannot use the implicit self property or call any of the instance methods.
Excerpt from: Apple Inc. "Fast programming language." interactive books. https://itun.es/de/jEUH0.l
This is how I will use from now on, because it does not bypass a useful function that does not allow nil for variables. For my example, it would look like this:
class GradientView: UIView { var gradientLayer: CAGradientLayer = { return CAGradientLayer() }() func commonInit() { gradientLayer.frame = self.bounds } init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) commonInit() } init(frame: CGRect) { super.init(frame: frame) commonInit() } }