0
0
Swiftprogramming~20 mins

Preventing overrides with final in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Final Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of overriding a final method
What will be the output of this Swift code?
Swift
class Vehicle {
    final func start() {
        print("Vehicle started")
    }
}

class Car: Vehicle {
    override func start() {
        print("Car started")
    }
}

let myCar = Car()
myCar.start()
ARuntime error
BCar started
CVehicle started
DCompile-time error: Cannot override 'final' method
Attempts:
2 left
💡 Hint
Remember what the 'final' keyword means for methods in Swift.
Predict Output
intermediate
2:00remaining
Output when subclass tries to override a non-final method
What will be printed when running this Swift code?
Swift
class Animal {
    func sound() {
        print("Some sound")
    }
}

class Dog: Animal {
    override func sound() {
        print("Bark")
    }
}

let pet: Animal = Dog()
pet.sound()
ABark
BSome sound
CCompile-time error: Cannot override method
DRuntime error
Attempts:
2 left
💡 Hint
Check if the method is marked final or not.
🔧 Debug
advanced
2:00remaining
Identify the error caused by final class inheritance
What error will this Swift code produce?
Swift
final class Calculator {
    func add(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
}

class AdvancedCalculator: Calculator {
    func multiply(_ a: Int, _ b: Int) -> Int {
        return a * b
    }
}
ARuntime error: Inheritance violation
BCompile-time error: Cannot inherit from final class 'Calculator'
CNo error, code runs fine
DCompile-time error: Method multiply missing override keyword
Attempts:
2 left
💡 Hint
Check the meaning of 'final' when applied to classes.
📝 Syntax
advanced
2:00remaining
Which code correctly prevents overriding a method?
Choose the Swift code snippet that correctly prevents subclasses from overriding the method 'display()'.
A
class Screen {
    final func display() {
        print("Display on screen")
    }
}
B
final func display() {
    print("Display on screen")
}
C
class Screen {
    func final display() {
        print("Display on screen")
    }
}
D
class Screen {
    func display() final {
        print("Display on screen")
    }
}
Attempts:
2 left
💡 Hint
The 'final' keyword must come before 'func' in method declaration inside a class.
🚀 Application
expert
3:00remaining
How many methods can be overridden?
Given the following Swift code, how many methods can subclasses override?
Swift
class Base {
    final func fixedMethod() {}
    func openMethod() {}
    private func privateMethod() {}
    fileprivate func fileMethod() {}
}
A1
B3
C2
D0
Attempts:
2 left
💡 Hint
Consider method access levels and the effect of 'final'.