What if one small change breaks your whole app? Learn how to stop that from happening!
Why Preventing overrides with final in Swift? - Purpose & Use Cases
Imagine you have a team working on a big app. You create a class with some important methods. But later, someone accidentally changes one of those methods in a subclass, breaking the app in ways no one expected.
Without a way to stop changes, bugs sneak in easily. You spend hours tracking down why a method behaves differently. It's slow, frustrating, and risky to let anyone override critical code.
The final keyword in Swift lets you mark classes or methods that should never be changed. This keeps your important code safe and clear, so no one can accidentally override it and cause problems.
class Vehicle { func start() { print("Starting vehicle") } } class Car: Vehicle { override func start() { print("Starting car") } }
class Vehicle { final func start() { print("Starting vehicle") } } class Car: Vehicle { // Cannot override start() now // override func start() { // This would cause a compile-time error // print("Starting car") // } }
It enables you to protect key parts of your code, making your app more reliable and easier to maintain.
Think of a banking app where the method to calculate interest must never change. Marking it final ensures no one accidentally alters it, keeping users' money calculations safe.
Prevent accidental changes to important code.
Make your app more stable and predictable.
Communicate clearly which parts of code are fixed.
Practice
What does the final keyword do in Swift?
Solution
Step 1: Understand the purpose of
Thefinalfinalkeyword in Swift is used to stop classes or methods from being changed by subclasses.Step 2: Identify what
It prevents overriding methods or subclassing classes, ensuring the code stays as originally designed.finalpreventsFinal Answer:
Prevents a class or method from being overridden or subclassed -> Option DQuick Check:
finalstops overrides = A [OK]
- Confusing final with constant variables
- Thinking final allows subclassing
- Mixing final with async keyword
Which of the following is the correct way to declare a method that cannot be overridden in Swift?
class Vehicle {
_____ func startEngine() {
print("Engine started")
}
}Solution
Step 1: Identify the keyword to prevent overriding
In Swift, thefinalkeyword is used before a method to stop it from being overridden in subclasses.Step 2: Check the method declaration
Placingfinalbeforefunccorrectly marks the method as non-overridable.Final Answer:
final -> Option CQuick Check:
Usefinalbefore func to prevent override [OK]
- Using override keyword incorrectly
- Confusing static with final
- Using mutating which is for structs
What will happen when you run this Swift code?
class Animal {
final func sound() {
print("Animal sound")
}
}
class Dog: Animal {
override func sound() {
print("Bark")
}
}
let pet = Dog()
pet.sound()Solution
Step 1: Identify the use of final in the base class
The methodsound()inAnimalis marked asfinal, so it cannot be overridden.Step 2: Check the subclass method override
TheDogclass tries to overridesound(), which causes a compile-time error because overriding a final method is not allowed.Final Answer:
Compile-time error due to overriding a final method -> Option BQuick Check:
Overriding final method = Compile error [OK]
- Assuming it prints "Bark"
- Thinking it prints base method output
- Expecting runtime error instead of compile error
Find the error in this Swift code and fix it:
final class Vehicle {
func drive() {
print("Driving")
}
}
class Car: Vehicle {
override func drive() {
print("Car driving")
}
}Solution
Step 1: Identify the use of final on the Vehicle class
TheVehicleclass is marked asfinal, so it cannot be subclassed.Step 2: Check subclass declaration
TheCarclass tries to subclassVehicle, which causes a compile-time error because subclassing a final class is not allowed.Final Answer:
Removefinalfrom Vehicle class -> Option AQuick Check:
Subclassing final class = Error; remove final [OK]
- Trying to override without removing final
- Adding final to subclass instead of base
- Changing class to struct unnecessarily
You want to create a base class BankAccount with a method calculateInterest() that should never be changed by subclasses. However, subclasses can add new methods. How should you declare BankAccount and calculateInterest()?
Solution
Step 1: Understand the requirement for subclassing
The base classBankAccountshould allow subclasses, so it must NOT befinal.Step 2: Protect the method from being overridden
MarkcalculateInterest()asfinalto prevent subclasses from changing it.Final Answer:
DeclareBankAccountnormally andcalculateInterest()asfinal-> Option AQuick Check:
final method, normal class = C [OK]
- Making the whole class final, blocking subclassing
- Not marking method as final, allowing override
- Using struct instead of class incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
