What's difference between final variables and non-final variables :
var someVar = 5
final var someFinalVar = 5
and
let someLet = 5
final let someFinalLet = 5
let is used to declare an immutable constant. You cannot change the value of it later. var is used to create a mutable variable that you can change later.
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.
The main purpose of using a final class is to prevent the class from being inherited (i.e.) if a class is marked as final, then no other class can inherit any properties or methods from the final class. If the final class is extended, Java gives a compile-time error.
Since classes are reference objects the only difference between let and var is the ability to reassign the variable to a different class of the same type. The let and var keywords do not affect the ability to change a variable on a class.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With