May 2, 2020

Readonly properties

In a struct you can mark a property readonly like

struct Example1 {
    private(set) var value: Int

This is another way of marking a property readonly

struct Example2 {
    let value: Int

There is an important difference though, the below code will compile just fine

var example1 = Example(value: 10)
example1.value = 20

while below code will not compile with error: cannot assign to property: 'value' is a 'let' constant

var example2 = Example2(value: 10)
example2.value = 20

and by using private(set) you can provide a default value to your property, and initializer can be called

with or without an argument.

Tagged with: