Ch11 Property wrappers

Hi @audrey

Hope this post finds you well :slight_smile: Can I please ask you to explain in other words (if time allows, with an example would be great) your following sentence (page 280)?

projectedValue is … or a projection of the object that creates bindings to its properties?

What’s a projection of the object?
Have we ever used that in the past chapters?

Thanks for your kind help :pray:

hi Omar! I actually just copied that wording from Apple’s documentation, but I’ll explain it more when we update this book (soon).

In this chapter, you learn about State, Binding and Environment for wrapping values and value data types like struct or enum. Putting $ in front of the value’s name gives you write access because it “projects” the value out of the wrapper.

Then you learn about StateObject and ObservedObject for wrapping a class type. In the Note, it says you can pass $myThings if you need access to more than one property of the class. This is a projection of the myThings object, which creates bindings to the object’s properties.

Property wrappers are a much more general topic in Swift: You can create your own property wrappers. These must have a wrappedValue property but they don’t need to have a projectedValue property. Some resources:

  • I think Donny Wals’ article is the easiest to follow, but the example is kind of generic.
  • John Sundell’s article has a good example of how you might actually use your own property wrapper. Maybe work back and forth between these two articles, plus a little of the next:
  • The swift.org book’s section on Properties (scroll down to Property Wrappers) is more about “how” than “why”.
  • Our Expert Swift book, section 14.5 (scroll down to Property Wrappers) gives you an idea of how Published works.
1 Like