swiftclassinitializationconvenience-methods

In Swift, get syntax error in convenience initializer when creating an object


I know a little about how to use convenience initializer and designated initializer.Here is a sample class called ClassA

class ClassA {
    var number:Int

    convenience init(){
        self.init(newNumber: 10)
    }

    init(newNumber: Int) {
        self.number = newNumber;
    }
}

This class works well but I got some trouble when implementing another class called Base. Here is the code:

class Base {
    var classObject:ClassA

    init(object: ClassA) {
        self.classObject = object
    }

    convenience init(){
        self.init(object: ClassA.init())
    }
}

In the convenience initializer of class Base, I call the convenience initializer of ClassA and take it as the argument of the designated initializer of Base.

However, I get two syntax errors.

  1. Expected member name or constructor call after type name.
  2. () is not convertible to Class A.

If I use

self.init(object: ClassA.init(newNumber: 10))

instead of

self.init(object: ClassA.init())

Then the first error disappears. It seems that the convenience initializer of ClassA is not recognized.


Solution

  • try to use self.init(object: ClassA())