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?
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.