Reputation: 2822
In Swift, we denote an immutable variable with let
.
What I don't understand is why you change their properties. For example:
let lbl = UILabel()
lbl.textAlignment = .Right()
Why can you change textAlignment
? By virtue of mutating the property, haven't we also mutated the variable lbl
that was supposed to be constant?
Upvotes: 9
Views: 3201
Reputation: 122429
Class types are reference types -- the value is a pointer to an object. Not being able to change it simply means not changing the reference, to point to another object. It does not have anything to do with what you can do with the object being pointed to.
Upvotes: 3
Reputation: 6657
According to the Swift Programming Language, the properties of constant structs are also constant, but constant classes can have mutable properties.
In their words,
If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties...
The same is not true for classes, which are reference types. If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.
Upvotes: 16