为什么不可变对象的属性在Swift中是可变的? [英] Why are properties of an immutable object mutable in Swift?

查看:96
本文介绍了为什么不可变对象的属性在Swift中是可变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,我们用let表示不可变的变量.

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()

为什么要更改textAlignment?通过对属性进行变异,我们不是也对应该不变的变量lbl进行了变异吗?

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?

推荐答案

根据

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

用他们的话来说,

如果您创建一个结构实例并将该实例分配给常量,则即使该实例的属性被声明为变量属性,也无法对其进行修改...

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.

这篇关于为什么不可变对象的属性在Swift中是可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆