PGDev
PGDev

Reputation: 24341

private(set) with let properties - 'private(set)' modifier cannot be applied to read-only properties

I'm already aware of how private(set) works. But the below code is give compile-time error,

class Person {
    private(set) let name: String //Error.
    private(set) let age: Int //Error.

    init(name: String, age: Int){
        self.name = name
        self.age = age
    }
}

Error:

'private(set)' modifier cannot be applied to read-only properties

Since name and age are not read-only properties, it shouldn't give such an error.

If I use let instead of var, it is working fine. Just trying to know why?

Upvotes: 2

Views: 2782

Answers (5)

vadian
vadian

Reputation: 285132

private(set) let is a contradiction in terms. Any setter requires a variable.

Please be aware that assigning a default value to a property is not setting the property in terms of initialization. For this reason the didSet property observer is not called after assigning a default value to a property.

In Swift there is only one case to use private(set): If the class contains code which modifies the variable

class Foo {
    let name : String
    private(set) var expiryDate : Date

    init(name: String, expiryDate: Date){
        self.name = name
        self.expiryDate = expiryDate
    }

    func extendExpiryDate(to newDate : Date) {
       expiryDate = newDate
    }
}

If the property is only initialized during init it's a constant – as correctly mentioned in the other answers – so declare it as let constant. Unlike other programming languages Swift provides explicit constants with the benefit of more security, less memory usage and better performance.

Upvotes: 3

Sahil Manchanda
Sahil Manchanda

Reputation: 10012

From the Swift.org under Getters and Setters

You can give a setter a lower access level than its corresponding getter, to restrict the read-write scope of that variable, property, or subscript. You assign a lower access level by writing fileprivate(set), private(set), or internal(set) before the var or subscript introducer.

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

Upvotes: 0

Jawad Ali
Jawad Ali

Reputation: 14407

Let are constants ... you cant change their value one you assign them. Thats why they are considered readOnly ... so error is valid ... either convert them to var if you want to set them after assign them any value or remove private(set) and make them just private

happy coding =)

Upvotes: 1

Raildex
Raildex

Reputation: 4766

You don't need a private setter when it is a let constant. Just initialize it in the constructor or on the same line as the declaration.

If you want to change it outside of the constructor, you need to make it a var

Upvotes: 0

user652038
user652038

Reputation:

They are read-only, because you’ve declared them with let, not var.

Upvotes: 0

Related Questions