So I'm 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!
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.
Open - same as public, only difference is you can subclass or override outside the module. Fileprivate - As the name say's, data members and member functions are accessible within the same file. Private - This is where you can have access within the scope of function body or class.
Swift provides five different access levels for entities within your code.
An open class member is accessible and overridable outside of the defining module. A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.
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.
You assign a lower access level by writing private(set)
.
Its works like Public getter and Private setter.
//MARK:- Foo
class Foo {
private var name: String
private var ID: String
//initialize
init(name:String, ID:String){
self.name = name
self.ID = ID
}
}
We will get an error when to try to access private
variable.
But we can fix this error in a single line by changing private
access level to private(set)
.
//MARK:- Foo
class Foo {
private(set) var name: String
private var ID: String
//initialize
init(name:String, ID:String) {
self.name = name
self.ID = ID
}
}
So you can easy access the private variable, constant, property, or subscript.
//Access class value from Foo
let fooObjc = Foo.init(name: "test", ID: "9900")
print(fooObjc.name)
Use fileprivate(set)
, private(set)
, and internal(set)
to change the access level of this synthesized setter in exactly the same way as for an explicit setter in a computed property.
This property can be read, but cannot be set from the outside.
Ref: Click the link to know more
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