How Does "Public Private(Set)" Access Modifiers Work?

How Does "Public Private(Set)" Access Modifiers Work?

So im going through the Apple docs here - Apple Docs

Then I ran into this..

public struct TrackedString {
    public private(set) var numberOfEdits = 0
    public var value: String = "" {
        didSet {
            numberOfEdits += 1
        }
    }
    public init() {}
}

How does adding public private(set) exactly work? If you can show some easier examples/explanation that would be amazing!

2 Answers

This just means that the getter for numberOfEdits is public, but the setter is private. There's nothing more to it.

The reason in this case is so that you can read numberOfEdits publicly, but you can only set it via changing value. If it were fully public, then anyone could set it, but if it were only settable, then the didSet in value couldn't modify it. private(set) is a compromise between those two.

2

This property can be read, but cannot be set from the outside

Ref: Click the link to know more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.