Sobes.tech
Junior — Middle

How can object composition be implemented within the __init__ method?

sobes.tech AI

Answer from AI

In iOS (Swift), object composition within the init method is implemented by creating and initializing nested objects as class properties. In the init constructor, you create instances of the necessary components and assign them to their properties.

Example:

class Engine {
    var horsepower: Int
    init(horsepower: Int) {
        self.horsepower = horsepower
    }
}

class Car {
    let engine: Engine
    let model: String

    init(model: String, horsepower: Int) {
        self.model = model
        self.engine = Engine(horsepower: horsepower) // composition of Engine object inside Car
    }
}

let myCar = Car(model: "Tesla", horsepower: 500)

In this example, the Car object contains an Engine object inside it, which is created and initialized in the init constructor. This is object composition.

How can object composition be implemented within the… - sobes.tech