问题
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
}
}
Error:
'private(set)' modifier cannot be applied to read-only properties
Since name
and age
are not read-only properties, it shouldn't give such an error.
If I use let
instead of var
, it is working fine. Just trying to know why?
回答1:
private(set) let
is a contradiction in terms. Any setter requires a var
iable.
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.
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
}
}
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.
回答2:
Let are constants ... you cant change their value one you assign them. Thats why they are considered readOnly ... so error is valid ... either convert them to var if you want to set them after assign them any value or remove private(set) and make them just private
happy coding =)
回答3:
They are read-only, because you’ve declared them with let
, not var
.
回答4:
You don't need a private setter when it is a let
constant.
Just initialize it in the constructor or on the same line as the declaration.
If you want to change it outside of the constructor, you need to make it a var
回答5:
From the Swift.org under Getters and Setters
You can give a setter a lower access level than its corresponding getter, to restrict the read-write scope of that variable, property, or subscript. You assign a lower access level by writing fileprivate(set), private(set), or internal(set) before the var or subscript introducer.
Related post: Swift: What does this error: 'private(set)' modifier cannot be applied to read-only properties mean?
来源:https://stackoverflow.com/questions/60446284/privateset-with-let-properties-privateset-modifier-cannot-be-applied-to