Why do immutable object properties change in Swift?

Swift denotes an immutable variable with let .

I do not understand why you are changing your properties. For example:

 let lbl = UILabel() lbl.textAlignment = .Right() 

Why can you change textAlignment ? Due to the property mutation, didn’t we also mutate the lbl variable, which should have been constant?

+7
immutability swift
source share
2 answers

According to the Swift Programming Language, the properties of constant structures are also constant, but constant classes can have mutable properties.

According to them,

If you create an instance of a structure and assign this instance to a constant, you cannot change the properties of instances, even if they were declared as property variables ...

The same does not apply to classes that are reference types. If you assign an instance of a reference type to a constant, you can still change these properties of instance variables.

+14
source share

Class types are reference types - this is a pointer to an object. Failure to change it simply means not changing the link, but pointing to another object. This has nothing to do with what you can do with the object that it points to.

+3
source share

All Articles