InterviewSolution
Saved Bookmarks
| 1. |
class SwiftBasics { static func test() { let emp1 = Employee(name: "John", id: 10) let emp2 = Employee(name: "John", id: 10) print("\(emp1 == emp2)") } } struct Employee { var name:String var id:Int init(name:String, id:Int) { self.name = name self.id = id } } |
|
Answer» There will be a compilation error. The derived class Car calls the init method of superclass before its stored property, model gets INITIALISED. SWIFT does 2 phase INITIALIZATION, in first phase memory is allocated and all stored properties get initialized starting from the derived classes and then its superclass. Then in the SECOND phase, all customizations of the properties are done, in the init method. The correct code will be : class Car:Transport { var model:String init(model:String){ self.model = model super.init(type: "Car") self.model = "\(self.model) - type \(self.type)" print("\(self.model)") } } The RESULT will be Transport - Car Maruti - type Car |
|