0
0
Swiftprogramming~10 mins

Base class and subclass in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a base class named Vehicle.

Swift
class [1] {
    var speed: Int = 0
}
Drag options to blanks, or click blank then click option'
ACar
BTransport
CBike
DVehicle
Attempts:
3 left
💡 Hint
Common Mistakes
Using a subclass name like Car instead of the base class name Vehicle.
2fill in blank
medium

Complete the code to declare a subclass named Car that inherits from Vehicle.

Swift
class Car: [1] {
    var brand: String = ""
}
Drag options to blanks, or click blank then click option'
AVehicle
BMachine
CBike
DTransport
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong class name after the colon that is not the base class.
3fill in blank
hard

Fix the error in the subclass initializer to call the base class initializer.

Swift
class Vehicle {
    var speed: Int
    init(speed: Int) {
        self.speed = speed
    }
}

class Car: Vehicle {
    var brand: String
    init(brand: String, speed: Int) {
        self.brand = brand
        [1]
    }
}
Drag options to blanks, or click blank then click option'
Aself.init(speed: speed)
BVehicle.init(speed)
Csuper.init(speed: speed)
Dinit(speed)
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call the base class initializer without super.
Calling self.init inside the initializer causing recursion.
4fill in blank
hard

Fill both blanks to override the base class method and add a new method in the subclass.

Swift
class Vehicle {
    func description() -> String {
        return "Vehicle moving at speed 0"
    }
}

class Car: Vehicle {
    override func [1]() -> String {
        return "Car moving at speed 0"
    }
    func [2]() -> String {
        return "This is a car"
    }
}
Drag options to blanks, or click blank then click option'
Adescription
Binfo
Cdetails
Dsummary
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name for the overridden method.
Forgetting the override keyword.
5fill in blank
hard

Fill all three blanks to create a subclass that overrides a method and calls the base class method inside it.

Swift
class Vehicle {
    func move() -> String {
        return "Vehicle is moving"
    }
}

class Bike: Vehicle {
    override func [1]() -> String {
        let baseMessage = super.[2]()
        return baseMessage + ", Bike is moving fast"
    }
    func [3]() -> String {
        return "Bike details"
    }
}
Drag options to blanks, or click blank then click option'
Amove
Cdetails
Dinfo
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling the base class method inside the override.
Using different method names for override.