具有let属性的private(set)-'private(set)'修饰符不能应用于只读属性 [英] private(set) with let properties - 'private(set)' modifier cannot be applied to read-only properties
问题描述
我已经知道 private(set)
的工作方式。但是下面的代码给出了编译时错误,
I'm already aware of how private(set)
works. But the below code is give compile-time error,
class Person {
private(set) let name: String //Error.
private(set) let age: Int //Error.
init(name: String, age: Int){
self.name = name
self.age = age
}
}
错误:
'private(set)'修饰符不能应用于只读属性
'private(set)' modifier cannot be applied to read-only properties
因为 name
和 age
不是只读属性,不应给出这样的错误。
Since name
and age
are not read-only properties, it shouldn't give such an error.
如果我使用 let
而不是 var
,它可以正常工作。只是想知道为什么?
If I use let
instead of var
, it is working fine. Just trying to know why?
推荐答案
private(set)let
是就矛盾而言。任何设置器都需要一个 var
iable。
private(set) let
is a contradiction in terms. Any setter requires a var
iable.
请注意,为属性分配默认值不是设置。因此,在为属性分配默认值后,不会调用 didSet
属性观察器。
Please be aware that assigning a default value to a property is not setting the property in terms of initialization. For this reason the didSet
property observer is not called after assigning a default value to a property.
在Swift中仅使用 private(set)
的一种情况:如果该类包含修改变量的代码
In Swift there is only one case to use private(set)
: If the class contains code which modifies the variable
class Foo {
let name : String
private(set) var expiryDate : Date
init(name: String, expiryDate: Date){
self.name = name
self.expiryDate = expiryDate
}
func extendExpiryDate(to newDate : Date) {
expiryDate = newDate
}
}
如果仅在 init
是一个常量(如在其他答案中正确提到的那样),因此将其声明为 let
常量。与其他编程语言不同,Swift提供了显式常量,具有更高的安全性,更少的内存使用量和更好的性能。
If the property is only initialized during init
it's a constant – as correctly mentioned in the other answers – so declare it as let
constant. Unlike other programming languages Swift provides explicit constants with the benefit of more security, less memory usage and better performance.
这篇关于具有let属性的private(set)-'private(set)'修饰符不能应用于只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!