0
0
Swiftprogramming~10 mins

Why inheritance is class-only in Swift - Test Your Understanding

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

Complete the code to declare a class that inherits from another class.

Swift
class Dog: [1] {
    func bark() {
        print("Woof!")
    }
}
Drag options to blanks, or click blank then click option'
Aenum
Bstruct
Cprotocol
DAnimal
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to inherit from a struct or protocol.
2fill in blank
medium

Complete the code to override a method in a subclass.

Swift
class Animal {
    func sound() {
        print("Some sound")
    }
}

class Cat: Animal {
    override func [1]() {
        print("Meow")
    }
}
Drag options to blanks, or click blank then click option'
Abark
Bmeow
Csound
Dnoise
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name that does not exist in the parent class.
3fill in blank
hard

Fix the error in the code by choosing the correct type that supports inheritance.

Swift
[1] Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
    }
}

class Car: Vehicle {
    var brand: String
    init(brand: String, wheels: Int) {
        self.brand = brand
        super.init(wheels: wheels)
    }
}
Drag options to blanks, or click blank then click option'
Aclass
Bstruct
CVehicle
Dprotocol
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to inherit from a struct or protocol.
4fill in blank
hard

Fill both blanks to create a subclass that calls the superclass initializer.

Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Student: [1] {
    var id: Int
    init(name: String, id: Int) {
        self.id = id
        [2].init(name: name)
    }
}
Drag options to blanks, or click blank then click option'
APerson
Bsuper
Cstruct
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using self.init instead of super.init to call the superclass initializer.
5fill in blank
hard

Fill all three blanks to define a class-only protocol and a class that conforms to it.

Swift
protocol [1]: [2] {
    func play()
}

class Guitarist: [3] {
    func play() {
        print("Playing guitar")
    }
}
Drag options to blanks, or click blank then click option'
APlayable
BAnyObject
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to restrict protocols to structs or enums.