In Objective-C, I often move the generic initialization code to my own method, and then I call this method from different assigned class initializers. Like this:
- (void)commonInit { _gradientLayer = [CAGradientLayer layer]; _gradientLayer.frame = self.bounds; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; [self commonInit]; return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; [self commonInit]; return self; }
In Swift, this template does not work, because you basically need to use a "two-stage init". First you need to assign the variables of your own subclass, and then call super.init , and only then will you be allowed access to yourself. eg:.
init(coder aDecoder: NSCoder!) { // initial assignment must be done first gradientLayer = CAGradientLayer() // no calls to self allowed super.init(coder: aDecoder) // calls to self allowed gradientLayer.frame = self.bounds /* ... */ }
I can easily move the "second phase", the setup that happens after super.init using my own method. However, I cannot transfer the "first phase", the initial assignment to my own method, because the method call includes a self call, which is not resolved before the super.init call.
Isn't there enough way to transfer the original assignment to your own method? I really don't want to duplicate all assignments in various init methods.
swift
Matthias Bauch Jun 05 '14 at 3:32 2014-06-05 03:32
source share