-1

I've got the following classes:

class A {
    
    let age:Int
    
    init(age: Int) {
        self.age = age
    }
}

extension A {
    convenience init?(ageString: String) {
        guard let age = Int(ageString) else { return nil}
        self.init(age: age)
    }
}

class B: A {
    
    private var name = ""
    
    init(name: String) {
        self.name = name
        super.init(age: 0)
    }
}

When I try to run B(ageString: "1") I will get an error because that init doesn't exist.

But if B doesn't have any init methods and I make name public, it won't complain. But that's not what I want.

Is this because init?(ageString: String) { is a convenience method, I can't do it non convenience because is created in an extension.

Are not the convenience init method inherited if there are designated methods in B?

xarly
  • 2,054
  • 4
  • 24
  • 40

2 Answers2

2

First of all don't you get an error that super is not called in init(name:)?

The convenience initializer is only available if you implement (override) init(age in B

override init(age: Int) {
    super.init(age: age)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Yes, sorry I get an error. So I would have to override all the init methods of `class A` in `B` , that's a bit...annoying Thanks for the help – xarly May 24 '23 at 12:59
  • @xarly It's not "annoying". Swift is helping you get initializers right. Believe the compiler. – matt May 24 '23 at 13:08
  • I think it's a bit annoying because the only reason I've got a `convenience` init is because is in an extension and I got it in a extension because it uses and object from another module ( in my real case, not in this example ), so I only need to import that module in the extension file. The class B should not be aware of this, instead B has to override all the methods from A because someone else creates an extension with a `convenience` init of A. Maybe I'm approaching this from the wrong way... – xarly May 24 '23 at 13:13
1

Are not the convenience init method inherited if there are designated methods in B?

No. Implementing a designated initializer in a subclass blocks inheritance of initializers from the superclass — unless you explicitly override, in the subclass, all the designated initializers of the superclass.

matt
  • 515,959
  • 87
  • 875
  • 1,141