Chapter 3. Writing cleaner properties
This chapter covers
- How to create getter and setter computed properties
- When (not) to use computed properties
- Improving performance with lazy properties
- How lazy properties behave with structs and mutability
- Handling stored properties with behavior
Cleanly using properties can thoroughly simplify the interface of your structs, classes, and enums, making your code safer and easier to read and use for others (and your future self). Because properties are a core part of Swift, following the pointers in this chapter can help the readability of your code straight away.
First, we cover computed properties, which are functions that look like properties. Computed properties can clean up the interface of your structs and classes. You’ll see how and when to create them, but also when it’s better to avoid them.
Then we explore lazy properties, which are properties that you can initialize at a later time or not at all. Lazy properties are convenient for some reasons, such as when you want to optimize expensive computations. You’ll also witness the different behaviors lazy properties have in structs versus classes.