0

I have converted an Objective-C method into Swift. And then, into the Swift code i am getting this error. I have no tied what i have done wrong.

Objective-C Code

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super initWithCoder:aDecoder])) {
        [self loadChecklistItems];
    }
    return self;
}

Swift 2.2 code

convenience required init(coder aDecoder: NSCoder) {
    if (self.init(coder: aDecoder)) {  // ERROR Here
        self.loadChecklistItems()
    }
}

Here is the screenshot of Swift code

Please tell me what i have done wrong and what will be the right code.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

0

Just call the initializer directly:

convenience required init(coder aDecoder: NSCoder) {
    self.init(coder: aDecoder)
    self.loadChecklistItems()
}

However, note that your code is making an infinite cycle of calls. Are you sure you don't want to call super.init(...)? Also, I think that this is not a convenience initializer:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.loadChecklistItems()
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
0

That initializer is failable, meaning it can return nil. The syntax for a failable initializer in Swift is:

convenience required init?(coder aDecoder: NSCoder) {  // Note the question mark after init

Additionally, if you call that initializer from within itself, your code will infinitely loop. I think you mean to do:

convenience required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)  // call super.init, not self.init
    self.loadChecklistItems()
}
Daniel Hall
  • 13,457
  • 4
  • 41
  • 37