Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set 'setter' of an computed property to private?

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

        }
    }
}
like image 774
Thor Avatar asked Mar 14 '16 22:03

Thor


People also ask

What is private set var Swift?

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.

What is willSet and didSet in Swift?

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.

What is the difference between a computed property and a property set to a closure in Swift?

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.

What is the use of private set in Swift?

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.


1 Answers

You do it the same way as for a stored property:

    private(set) var age: Int{
        get {
            return 10
        }
        set(newAge) {
            // setter code here
        }
    }
like image 186
rob mayoff Avatar answered Oct 07 '22 12:10

rob mayoff