Swift: What does this error: 'private(set)' modifier cannot be applied to read-only properties mean?

Viewed 2916

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
2 Answers

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.

Related