[Swift] Variable shapes that were not taught in the introductory book

1. The form of variables taught in the introductory book

python


var Ippanteki = 0

Or

python


var Ippanteki:Int = 0

2. Variable shapes that were not taught in the introductory book

The shape of variables that appear when looking at technical books

python


var notIppanteki:Int {
     return 1
}

The identity is Computed Property

The variable form described in 1 </ code> stores the value directly. Stored Property </ b> Is called.

On the other hand, the variables described in 2 </ code> are Computed Property </ b> Is what is called.

The Computed property is a variable that performs processing based on the values of other properties and returns the result.

There are read-only getters </ code> and writable setters </ code>.

The variables described this time are read-only getter </ code>. If it is read-only, get </ code> can be omitted.

Data type must be stated at the time of declaration

var notIppanteki:Int { return 1 }

It is necessary to describe the data type like this. If not stated,

Computed property must have an explicit type I get the error.

Computed Propaty must have a detailed type.

In other words, when declaring a calculated property, it is necessary to describe the data type!

Summary

I wanted to change the value of the variable according to the value of the saved userDefaults. Thanks to you, I was refreshed.

python


var computedPropaty:Int {
if UserDefaults.standard.bool(forKey: "ippanteki") {
    return 0
} else {
    return 1
}

reference

· Swift: After the variable {} · · This is the Comuputed property (get / set). Swift Read-Only Computed Properties