I am bit confused if we can create computed property which is read-only Somethig like:
extension ToMyClass {
private(set) var isEmpty: Bool {
return head == nil
}
}
While trying to create I got following error:
error: 'private(set)' modifier cannot be applied to read-only properties
Read-Only Computed PropertiesA computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but can't be set to a different value.
Using only private(set) means that the getter is internal - so not accessible outside the module.
In swift, we can create a read-only property by only defining a getter for a variable. Meaning no setter! Since the variable only has a getter, the compiler will throw an error when we try to assign a value to “sum”.
You are trying to set a modfier for a computed property, which is always read-only
The code below was taken from: The Swift Programming Language (Swift 4)
struct TrackedString {
private(set) var numberOfEdits = 0
var value: String = "" {
didSet {
numberOfEdits += 1
}
}
}
It should be a stored property
I got the same error but for a totally different reason. My code was as such:
protocol Foo {
var bar: String { get }
}
class Baz: Foo {
private (set) let bar: String // Error
init(bar: String) {
self.bar = bar
}
}
I just had to change:
private (set) let bar: String
to:
private (set) var bar: String
let
makes properties immutable and that was causing issues.
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