Member-only story

What is the final class in Swift?

Gurjit Singh
2 min readDec 20, 2023

--

Photo by Headway on Unsplash

In Swift, the final keyword is used to indicate that a class, method, or property cannot be overridden or subclassed. When you declare a class as final, it means that it's the end of the inheritance chain for that class, and it cannot be subclassed further.

Final Class:

final class MyClass {
// Class definition
}

By marking MyClass as final, you're explicitly stating that no other class can inherit from it. This can be beneficial in several scenarios:

  1. Preventing Subclassing: If you have a class whose design or behavior should not be modified or extended, marking it as final ensures that its functionality remains intact and cannot be altered by subclasses.
  2. Performance Optimization: The compiler can perform certain optimizations on final classes and methods because it knows they cannot be overridden.

Usage:

final class Vehicle {
// ...
}

// This will produce an error, as 'Car' cannot inherit from a 'final' class 'Vehicle'
class Car: Vehicle {
// ...
}

If you mark class final, it means that it’s the end of the inheritance chain for that class, and it cannot be subclassed further. If you try to implement inheritance it will produce an error, as Carcannot inherit from a finalclass Vehicle.

--

--

Gurjit Singh
Gurjit Singh

Written by Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me on twitter @gurjitpt and for more articles www.gurjit.co

No responses yet