Reputation: 2180
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
Upvotes: 9
Views: 4183
Reputation: 6893
Let's say, you have a struct -
struct StudentData {
let id: String
private(set) var maxScore: Int
var scoreNotUptoMark: Bool {
return maxScore < 60
}
init(id: String, score: Int) {
self.id = id
self.maxScore = score
}
mutating func scoreUp(by score: Int) -> Int {
self.maxScore = maxScore + score
return maxScore
}
}
If you add private(set) modifier to id
or scoreNotUptoMark
we will get an error stating -
private(set)' modifier cannot be applied to read-only properties
Have a look at the code, is there any way, one can set value to id
after it is initialized. No, right?
A constant can only be initialized when it is declared with value or from the initializer of the struct or class, it belongs to. Hence it is a read-only properly.
Same goes for scoreNotUptoMark
. Can you set any value to a computed properties? No, right?
So, by behavior, it is a read-only property
Upvotes: -1
Reputation: 36317
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.
Upvotes: 2
Reputation: 1443
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
Upvotes: 10