Search code examples
swiftinitializer

Why I cannot place a designated initliazer in to a extension of a class?


It works fine when I put a designated initializer into the structure's extension (please see the example as follow)

struct BaseOne {
    var a = 12
    var b = 22
}
extension BaseOne {
    init(a: Int){
        self.a = a
        self.b = 231
    }
}

However, when I do this for the class, thing were start to gone wrong

class BaseOne {
    var a = 12
    var b = 22
}
extension BaseOne {
    init(a: Int){  // Error message poped up here 
        self.a = a
        self.b = 231
    }
}

enter image description here

Can someone explain this for me?

Thanks


Solution

  • from the document

    All of the designated initializers for a class must be written within the class definition itself, rather than in an extension, because the complete set of designated initializers is part of the interface contract with subclasses of a class.

    Edit: Document link

    https://github.com/apple/swift/blob/master-next/docs/ObjectInitialization.rst