D4ttatraya
D4ttatraya

Reputation: 3404

Initialising mandatory properties in child class initialiser - Swift

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

Upvotes: 0

Views: 264

Answers (1)

Kazi Abdullah Al Mamun
Kazi Abdullah Al Mamun

Reputation: 1481

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!)")

Upvotes: 2

Related Questions