swift difference between final var and non-final var | final let and non-final let
The final
modifier is described in the Swift Language Reference, which says
final
Apply this modifier to a class or to a property, method, or subscript member of a class. It’s applied to a class to indicate that the class can’t be subclassed. It’s applied to a property, method, or subscript of a class to indicate that a class member can’t be overridden in any subclass.
This means without final
we can write:
class A {
var x: Int {return 5}
}
class B : A {
override var x: Int {return 3}
}
var b = B()
assert(b.x == 3)
but if we use final
in class A
class A {
final var x: Int {return 5}
}
class B : A {
// COMPILER ERROR
override var x: Int {return 3}
}
then this happens:
$ swift final.swift
final.swift:6:18: error: var overrides a 'final' var
override var x: Int {return 3}
^
final.swift:2:15: note: overridden declaration is here
final var x: Int {return 5}
Final variables can't be overridden in subclasses. It also hints this to the compiler which allows it to inline the variable. It other words every time the compiler sees a final variable being used somewhere, it can immediately substitute the value. Whether or not the compiler actually does this is up to the compiler and whatever optimisations it knows/uses.