Search code examples
swiftcomputed-properties

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


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

Solution

  • 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