Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift difference between final var and non-final var | final let and non-final let

Tags:

swift

swift2

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
like image 347
kamran2142 Avatar asked Mar 05 '16 19:03

kamran2142


People also ask

What is the difference between VAR and let in Swift?

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.

What is final variable in Swift?

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.

What is the difference between a final class and other classes?

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.

What's the difference between VAR and let Which one would you choose for properties in a struct and why?

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.


1 Answers

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}
like image 177
Ray Toal Avatar answered Sep 21 '22 15:09

Ray Toal