0

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

Community
  • 1
  • 1
SLN
  • 4,772
  • 2
  • 38
  • 79
  • @LeoDabus But convenience initializer is not Designated initializer. It is the deleting initializer which calls Designated initializer to so some "job" – SLN Jul 08 '16 at 19:48

2 Answers2

2

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

Ali Kıran
  • 1,006
  • 7
  • 12
-1

This is because swift automatically generates initializers for you when working with structs. So this is valid

struct BaseOneStruct {
    var a: Int 
    var b: Int
}
let a = BaseOne(a: 12, b: 32)

even though there is no initializer. Classes do not do this for you however. For your code to work you would have to do something like this

class BaseOneClass {
    var a = 12
    var b = 22
    init() { }
}

extension BaseOneClass {
    convenience init(a: Int){ 
        self.init()
        self.a = a
        self.b = 231
    }
}

Also note that you are able to use the empty init BaseOneStruct() because you set values for your variables at their definition

Mr Flynn
  • 415
  • 2
  • 10
  • Quote from the document: Swit provides a default initializer for any structure or class that provides default values for al of its properties and does not provide at least one initializer itself. – SLN Jul 08 '16 at 19:54