Structs, computed properties and the usage of a getter

Official solution Module 1, Lesson 8:

struct Car {
    private var make = "Toyota"
    private var model = "Camry"
    private var year = "1999"
    private var details:String {
        year + " " + make + " " + model
    }
}

Alternative solution using a getter, which works too:

struct Car {
    private var make = "Fiesta"
    private var model = "Ford"
    private var year = "2018"
    var details: String {
        get {
            year + " " + make + " " + model
        }
    }
}

What’s the benefit of using a getter? Should one way become preferred over the other?

Computed properties are required to have a getter. They can optionally have a setter.

Writing:

var details: String {
    year + " " + make + " " + model
}

is equivalent to:

var details: String {
    get {
        year + " " + make + " " + model
    }
}

You only really need to explicitly mark a getter if you also have a setter. If your computed property is read-only, you can simplify the code by omitting the get keyword and the braces.

1 Like