I want to setup a variable using let
so that its not optional, won't change over time and doesn't require messy unwrapping to access each time. I know I can legally set it, but only inside one of the init
methods. The problem is that Swift requires you to override the init(coder aDecoder: NSCoder)
initializer. However I've never had an app that ever has that initializer called. Its always the init(frame: CGRect)
initializer that is called. So if I didn't have to override init(coder aDecoder: NSCoder)
then I'd just do the self.imageView = UIImageView.new()
in init(frame: CGRect)
and I'd be done, but the compiler complains that its not set in the other init as well. I tried making a sharedInit()
method that is called from both inits, but the compiler won't let me set the imageView
from there since it's read only outside of the init methods. How are you supposed to accomplish this without doing all of your init twice directly in the init methods?
class SuperCoolView : UIView {
let imageView: UIImageView
required init(coder aDecoder: NSCoder) {
sharedInit()
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
sharedInit()
super.init(frame: frame)
}
func sharedInit() {
self.imageView = UIImageView.new()
// Other similar shared init
}
}