Why are properties of an immutable object mutable in Swift?

谁说胖子不能爱 提交于 2019-12-22 05:10:34

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/25827643/why-are-properties-of-an-immutable-object-mutable-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!