9

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?

1
  • The variable/binding cannot be re-assigned to a different value; this alone says nothing about the mutability of the object that results from evaluation of the variable. This is the same as final/readonly variables/fields in Java and C#. Commented Sep 13, 2014 at 21:00

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, explains it perfectly. Will accept when I can.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.