I'm learning swift and coming across the following problem very often. I will have a class with a property that feels as if it should be a let
property as it will only be set once. I'd also like this child object to maintain a reference to its owner, which should also be a let
property, as the parent relationship will not change. The problem arises when the parent class subclasses another class and all let
properties need to be set before super.init ()
is run but requires a reference to self
to init.
Here's a quick example
class NodeView: UIView {
let _nodePlugView: NodePlugView
init (node: Node) {
_nodePlugView = NodePlugView (parentView: self)
super.init ()
}
}
Of course, I could just use var
for these _nodePlugView
but it doesn't feel quite right. Is there another pattern that people would recommend?
This is a good use case for an implicitly unwrapped optional.
The Apple documentation states:
“Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization.”
This means that you can use an implicitly unwrapped optional when a property depends on some aspect of self (but not the superclass) when it is initialised.
The property will be nil until it is set in the init()
method and then must never be nil again.
class NodeView: UIView {
var _nodePlugView: NodePlugView!
init (node: Node) {
super.init()
_nodePlugView = NodePlugView (parentView: self)
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments