【发布时间】:2021-07-14 06:29:03
【问题描述】:
我们都知道类的属性总是引用类型,但是有没有办法在类中创建一个值类型的属性呢?
类:
class Color {
var name : String!
init(name : String) {
self.name = name
}
}
利用:
let red = Color(name: "Red")
let yellow = red
print("red \(red.name ?? "")") // prints Red
print("yellow \(yellow.name ?? "")") // prints Red
// assigning a new value to yellow instance
yellow.name = "Yellow"
print("red \(red.name ?? "")") // prints Yellow
print("yellow \(yellow.name ?? "")") // prints Yellow
在为黄色实例赋值后,它也在改变红色实例的值。
【问题讨论】:
-
"类的属性总是引用类型" 不正确。如果你曾经在一个类中声明了
Int或String属性,你就会知道, -
嗨@Sweeper,感谢您的快速回复,我编辑我的问题,请检查
-
这与类是否具有引用类型或值类型属性无关。它与类
Color自身 是引用类型还是值类型有关。好吧,类总是引用类型,所以答案是否定的。
标签: ios swift class pass-by-reference pass-by-value