What is the output of this Swift code?
class Animal { func sound() -> String { return "Some sound" } } class Dog: Animal { override func sound() -> String { return "Bark" } } let pet: Animal = Dog() print(pet.sound())
Remember that subclass methods can replace base class methods when marked with override.
The Dog class overrides the sound() method of Animal. Even though the variable is typed as Animal, the actual object is a Dog, so sound() from Dog is called, printing "Bark".
What will be printed by this Swift code?
class Vehicle { var wheels: Int init(wheels: Int) { self.wheels = wheels } } class Bicycle: Vehicle { init() { super.init(wheels: 2) } } let bike = Bicycle() print(bike.wheels)
Check how the subclass calls the base class initializer.
The Bicycle class calls super.init(wheels: 2) to set the wheels property to 2. So printing bike.wheels outputs 2.
What error does this Swift code produce?
class Person { var name: String init(name: String) { self.name = name } } class Employee: Person { var id: Int init(id: Int) { self.id = id } }
Subclass initializers must call the base class initializer to initialize inherited properties.
The Employee initializer sets id but does not call super.init(name:). This causes a compile-time error because the inherited property name is not initialized.
What is the output of this Swift code?
class Printer { func printMessage() { print("Base message") } } class CustomPrinter: Printer { override func printMessage() { super.printMessage() print("Custom message") } } let p = CustomPrinter() p.printMessage()
Look at how super.printMessage() is used inside the subclass method.
The CustomPrinter overrides printMessage() but calls super.printMessage() first, printing "Base message" then "Custom message" on separate lines.
Given these Swift classes, how many stored properties does an instance of Manager have?
class Employee {
var name: String
var salary: Double
init(name: String, salary: Double) {
self.name = name
self.salary = salary
}
}
class Manager: Employee {
var department: String
init(name: String, salary: Double, department: String) {
self.department = department
super.init(name: name, salary: salary)
}
}Count all stored properties declared in base and subclass.
An instance of Manager has name and salary from Employee, plus department from Manager, totaling 3 stored properties.