Blog

[Swift] Properties

Published 1 min read

There seem to be about 3 things to know about properties.
Property, KeyPath, Property Observer (red)

Property is divided into Stored, Computed, and Type (blue), and the green below is the related stuff to know.
'Summary only'

Property

Stored Property

  1. Stores a value

  2. In a class, stored properties need an initialize implementation, but not in a struct.

  3. A struct implements initialize automatically

  4. If you don't want to implement initialize in a class, give it an initial value or make it optional

  5. With lazy, the instance used only once is initialized when the property is accessed (it may be initialized multiple times in multithreading)

Computed Property

  1. Doesn't store a value, and returns a computed value when you try to read the property

  2. Makes it look intuitive through get set implementation

Type Property

  1. It's called a type property because you can access the value through the type without using an instance

(For example, in class A, you access it as A.x instead of A().x)

  1. You create a type property by adding static, and it has a single unique value

  2. Stored type properties are lazily evaluated even without the lazy keyword (guaranteed to be initialized only once even in multithreading)

KeyPath

With KeyPath you can reference just the location of a property.
And you can access the property with it through Subscript.
Also, with KeyPath you can use it instead of closures in map, compactMap, and filter for better readability.

Property Observer

You can have a function run automatically when a property's value changes
Those functions are made up of willSet and didSet,
willSet is called right before the value changes
didSet is called right after it changes

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub