0

I know if a function is marked as final, then it can't be overridden in subclass. But what if a property in a class is marked as final? I gave it a try and found it can be assigned a new value in subclass.

sevenkplus
  • 178
  • 1
  • 12

2 Answers2

4

Final on a property means that a subclass cannot modify the assignment logic of the property. It does not mean that the property value is immutable.

Without final, something like this would be allowed:

class X {
    var x: Int
}

class Y: X {
    override var x: Int {
        get { ... }
        set { ... }
    }
}
zneak
  • 134,922
  • 42
  • 253
  • 328
  • If I add getter and setter method to a stored property, will it become a computed property? Does it mean that it is meaningless to mark a stored property as final? – sevenkplus Aug 18 '15 at 15:35
  • Swift abstracts away the difference between stored properties and computed properties. From outside a class, there is no way to tell if a property is a stored property or a computed property, and both can override the other in a child class. As for `final` being "meaningless", it is as meaningful on properties as it is on methods. – zneak Aug 18 '15 at 19:24
1

Just as an addition to zneaks right answer, in Swift you can declare a property with let instead of var... So if you say

let myConstantProperty: String = "Peter"

No one will be able to change it... But thats just if you need a functionality like this...

Dennis Weidmann
  • 1,942
  • 1
  • 14
  • 16