top of page

Property wrappers in swift

Writer: Shubham BakshiShubham Bakshi

A person wrapping a gift

As the name suggests, property wrapper wraps the property with custom logic that gets executed whenever you try to set or get that property. It helps us in getting rid of a lot of boilerplate code as well as making the code more readable


As per swift documentation:

A property wrapper adds a layer of separation between code that manages how a property is stored and the code that defines a property

Consider a scenario where we’re maintaining the health of a character of certain game where it can vary from 0 to 100. However, based on hits received to the character or health points received, it can go below or exceed that range respectively; which is not acceptable (e.g. character was at 10 health and received a damage that is meant to cost 15 health points. So technically that takes the character to -5 health; which is not a valid thing).

 

Now how would we manage that scenario? Take a look:

This seems like too much code for a single property. Furthermore, this will get messier when we introduce more properties based on range; such as specialAbility


Role of Property wrappers


Requirements of property wrappers:

  1. @propertyWrapper keyword before the data type

  2. wrappedValue property inside that data type

What this will do is whenever you try to access the health property, it will access the wrappedValue property and use its getter. Similarly, setter will be called when you try to update the health value


When we use a property wrapper, we write the management code once when you define the wrapper, and then reuse that management code by applying it to multiple properties. This is how our code looks like after using property wrapper:

Bonus: For the ones paying close attention


If you look closely at the usage of our property wrapper in Character  , you’ll notice that we never specified wrappedValue for @Clamped even though the init of it requires wrappedValue. 


This is due to swift’s syntactic design for property wrappers. When a property wrapper is applied to a property, Swift automatically uses the property’s initial value as the wrappedValue argument for the wrapper’s initializer. This is a built-in behaviour of property wrappers.


However, this will only work in cases where you provide an initial value to the property and not with init based types. The property wrapper will fail to extract the value implicitly in the following case:

That’s it, folks! Happy Coding!

Site's author picture

Shubham Bakshi

Been coding since '13. Rode the Apple bandwagon in '18. Some can say it was love at first byte. I engineer apps with such finesse, they practically dance through your device. And if you're a dev feeling lost in the code jungle, fear not! I'm here to be your coding compass, guiding you through the wilderness of curly braces and semicolons.

Website logo
© Bits & Bytes w/ Bakshi. All rights reserved.
bottom of page