0

Heres my class hierarchy:

class Parent {
    var name: String
    var age: Int
    init(dict: [String: Any]) {
        age = dict["age"] as! Int
    }//ERROR: "Return from initializer without initializing all stored properties"
}

class Child: Parent {
    var school: String
    override init(dict: [String: Any]) {
        school = dict["school"] as! String
        super.init(dict: dict)

        name = dict["childname"] as! String
    }
}

If I initialise name property in Parent initialiser then it's working, but in my situation I want it to initialise in Child only.

Is there any way to handle this?

P.S. there are lots of properties in Parent like name those should be initialised in Child

D4ttatraya
  • 3,344
  • 1
  • 28
  • 50
  • 2
    That makes no sense, creating a Parent object must initialize all properties. If `name` exists only in a Child then make it a property of Child. – Martin R Apr 19 '18 at 18:21
  • 1
    There is absolutely no way to achieve what you want. An init method must initialise all the members. – gnasher729 Apr 19 '18 at 18:23

1 Answers1

2

Class/Struct properties can't be nil/null. You must initialize Class/Struct properties at the time of declare or inside Class/Struct's initializers. If you want properties remain nil/null and want to populate them later, you have to declare your variable/reference as Optional.

In your case make your name variable of Parent class as Optional like this var name: String?.

class Parent {
var name: String?
var age: Int
init(dict: [String: Any]) {
    age = dict["age"] as! Int
}
}

class Child: Parent {
var school: String
override init(dict: [String: Any]) {
    school = dict["school"] as! String
     super.init(dict: dict)
     name = dict["childname"] as! String
}
}

let dict: [String: Any] = ["childname":"Mamun", "school":"school name", 
"age": 12]
let child = Child(dict: dict)
print("Child name: \(child.name!)")