Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are properties of an immutable object mutable in Swift?

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?

like image 358
Jason Renaldo Avatar asked Sep 13 '14 20:09

Jason Renaldo


Video Answer


1 Answers

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.

like image 101
erdekhayser Avatar answered Oct 29 '22 01:10

erdekhayser