I have a hierarchy of 2 classes in Swift 2.0. Both classes can be instantiated by passing the arguments or by passing a JSON dictionary ([String: AnyObject]
) which contains the arguments.
The inits that directly take the arguments are designated inits
, while those that take the JSON are convenience inits
with the same signature.
class Thing {
let name : String
init(name: String){
self.name = name
}
convenience init(jsonNamed: String){
// read the json, parse and extract
// the name
self.init(name: "got this from JSON")
}
}
class SubThing : Thing{
var surname : String
init(name: String, surname: String){
self.surname = surname
super.init(name: name)
}
convenience init(jsonNamed: String){
self.init(jsonNamed: "got this from JSON")
// extract surname
self.surname = "Got this from json"
}
}
The convenience
init in SubThing
is not allowed to call the same init in super, and if I call it in self, it will cause an infinite recursion, as both methods have the same signature
.
If I make both json inits designated
ones, I can't call self.init(name:)
in Thing
, and I would have to repeat the same code in both initialisers in Thing
.
What's the best way to get around this kind of situation?