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.
This property can be read, but cannot be set from the outside