Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 626
manismku Avatar asked Aug 13 '17 12:08

manismku


People also ask

What is read-only property in Swift?

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.

What does private set mean in Swift?

Using only private(set) means that the getter is internal - so not accessible outside the module.

How do I make a Swift property read-only?

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”.


2 Answers

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

like image 190
Woof Avatar answered Oct 25 '22 21:10

Woof


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.

like image 2
mfaani Avatar answered Oct 25 '22 20:10

mfaani