0

I have a swift class which is a subclass of NSObject. The problem is when I try to define init in an extension. Consider this sample class:

public class Person: NSObject {
  public init(name: String) {
    self.name = name 
  }
}

So when I define init in an extension like this in my main app:

extension Person {
  @objc public convenience override init() {
    self.init(name: "test")
  }
}

and try to create object in objective-c like this:

[[Person alloc] init];

it gives me this error: 'init' is unavailable and it forces me to use initWithName

but when I define init inside the class and not extension, everything works:

public class Person: NSObject {
  public init(name: String) {
    self.name = name 
  }

  @objc public convenience override init() {
    self.init(name: "test")
  }
}

I'm sure the extension is available to my obj-c class and also have imported "ProjectTarget-Swift.h" to my obj-c file but have no idea why this doesn't work, anyone can help? Thanks

coder
  • 1
  • Might be related to this - https://stackoverflow.com/questions/38213286/overriding-methods-in-swift-extensions. The initializer is still a method in Objective-C. – Cristik Jun 21 '21 at 21:55
  • 1
    @Cristik thanks for pointing this out, it makes sense, because if I create other convenience inits in extension it works, it only doesn't allow `override init` :( – coder Jun 21 '21 at 22:02

0 Answers0