Using final stops other parts of your code from changing a class or method. This helps keep your code safe and clear.
0
0
Preventing overrides with final in Swift
Introduction
When you want to make sure a class cannot be changed by others.
When you want to stop a method from being changed in child classes.
When you want to protect important code from accidental changes.
When you want to improve performance by telling Swift the code won't change.
When you want to keep your design simple and clear.
Syntax
Swift
final class ClassName { // class code } class ParentClass { final func methodName() { // method code } }
You put final before class to stop the class from being inherited.
You put final before a method to stop it from being overridden in child classes.
Examples
This class
Animal cannot be inherited by any other class.Swift
final class Animal { func sound() { print("Some sound") } }
The method
start() cannot be changed in Car because it is marked final in Vehicle.Swift
class Vehicle { final func start() { print("Starting engine") } } class Car: Vehicle { // Trying to override start() here will cause an error }
Sample Program
This program shows a Bird class with a final method fly(). The Eagle class tries to override it but cannot. When we call fly() on an Eagle object, it runs the original method.
Swift
class Bird { final func fly() { print("Flying high") } } class Eagle: Bird { // Uncommenting the below code will cause an error // override func fly() { // print("Eagle flying") // } } let eagle = Eagle() eagle.fly()
OutputSuccess
Important Notes
Marking a class final means no other class can inherit from it.
Marking a method final means child classes cannot change how it works.
Using final can help your app run faster because Swift knows the code won't change.
Summary
final stops classes or methods from being changed.
Use it to protect important code and keep your design clear.
It can also help your program run better.