0
0
Swiftprogramming~10 mins

Overriding methods and properties 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 override the method describe() in the subclass.

Swift
class Animal {
    func describe() {
        print("I am an animal.")
    }
}

class Dog: Animal {
    override func [1]() {
        print("I am a dog.")
    }
}
Drag options to blanks, or click blank then click option'
Adescription
Bdescribe
CdescribeAnimal
DprintDescription
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name so the method is not actually overridden.
Forgetting the override keyword.
2fill in blank
medium

Complete the code to override the computed property description in the subclass.

Swift
class Vehicle {
    var description: String {
        return "A vehicle"
    }
}

class Car: Vehicle {
    override var [1]: String {
        return "A car"
    }
}
Drag options to blanks, or click blank then click option'
Adescription
Bdesc
Cinfo
Ddetails
Attempts:
3 left
💡 Hint
Common Mistakes
Changing the property name so it does not override.
Not using the override keyword.
3fill in blank
hard

Fix the error in the code by correctly overriding the method makeSound().

Swift
class Bird {
    func makeSound() {
        print("Chirp")
    }
}

class Parrot: Bird {
    override func [1]() {
        print("Squawk")
    }
}
Drag options to blanks, or click blank then click option'
AmakeSound
BmakeNoise
Csound
Dspeak
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name so it does not override.
Omitting the override keyword.
4fill in blank
hard

Fill both blanks to override the property speed with a getter and setter.

Swift
class Machine {
    var speed: Int = 0
}

class Car: Machine {
    override var [1]: Int {
        get {
            return super.[2]
        }
        set {
            super.speed = newValue
        }
    }
}
Drag options to blanks, or click blank then click option'
Aspeed
Bvelocity
Dpower
Attempts:
3 left
💡 Hint
Common Mistakes
Using different property names in the override and super access.
Forgetting the override keyword.
5fill in blank
hard

Fill both blanks to override a method with parameters and call the superclass method inside.

Swift
class Printer {
    func printMessage(_ message: String) {
        print("Printer: \(message)")
    }
}

class ColorPrinter: Printer {
    override func [1](_ message: String) {
        print("ColorPrinter:")
        super.[2](message)
        print("Done printing.")
    }
}
Drag options to blanks, or click blank then click option'
AprintMessage
CprintMsg
Dprint
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name so it does not override.
Not calling the superclass method correctly.