Understanding Swift’s Property Wrappers
Don’t be so lazy
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.4.1, and Swift 5.2.2
Prerequisites:
- You will be expected to be aware how to make a Single View Application in Swift, or a Hello World equivalent
- It would be helpful to understand something about lazy variables would be useful
- Property Wrappers rely on Generics in Swift
Terminology
lazy variables: A technique in that a property is only created when it is needed
Property Wrappers: A property wrapper adds a layer of separation between code that manages how a property is stored and the code that defines a property
Why use property wrappers?
Using Lazy in Swift is useful as it defers initialization of a value until its first access. This is equivalent functionality to wrapping a value in a computed get — lazy makes your code more elegant, easy to read and of course maintainable.
Here is an example of the lazy instantiation of a struct (if you follow along with the Playground, make sure you comment out one of the People
instances at a time or the…