How to distribute common initialization code between different assigned init methods?

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.

0
swift
Jun 05 '14 at 3:32
source share

No one has answered this question yet.

See similar questions:

45
How to implement two inputs with the same content without duplicating code in Swift?

or similar:

928
How do I call Objective-C code from Swift?
47
How to write init methods of UIViewController in Swift
eleven
How to override UIView initializer in Swift 1.0
9
"Using self in a method before super.init initializes self" cannot initiate properties by invoking a method
four
Class Extension for NSCoding Protocol Compliance
2
Using self in a property access model before super.init initializes self super.init (brand: brand, model: model)
one
Initializing a fast subclass of objc class
one
draw (_ rect: CGRect) does not receive a call in user view
one
Create a custom table table cell using swift
one
How to decompose Swift class initialization to avoid redundant code?



All Articles