I know how to set 'setter' of an stored property to private (e.g. public private(set) var name: String = "John"
) but how do we set 'setter' of an computed property to private? In this case the 'setter' for the variable 'age
'. When I tried to put an keyword private in front of set(newAge){}
, XCode display an error. So is it possible to set 'setter' of an computed property to private?
public class Person {
public private(set) var name: String = "John"
var age: Int{
get {
return 10
}
set(newAge){ // how to set this setter to private so to restrict modification
}
}
}
public(get) private(set) var foo:String. to be doubly explicit. The goal is that foo should have a getter which is accessible from outside the module, but a private setter. Using only private(set) means that the getter is internal - so not accessible outside the module.
willSet is called before the data is actually changed and it has a default constant newValue which shows the value that is going to be set. didSet is called right after the data is stored and it has a default constant oldValue which shows the previous value that is overwritten.
In short, the first is a stored property that is initialized via a closure, with that closure being called only one time, when it is initialized. The second is a computed property whose get block is called every time you reference that property.
However, the access level for the numberOfEdits property is marked with a private(set) modifier to indicate that the property's getter still has the default access level of internal, but the property is settable only from within code that's part of the TrackedString structure.
You do it the same way as for a stored property:
private(set) var age: Int{
get {
return 10
}
set(newAge) {
// setter code here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With