Property Wrappers in Swift

Ankur JAIN
Analytics Vidhya
Published in
3 min readAug 18, 2020

Properties in Swift are used to hold some kind of data. Sometimes these properties have some kind of logic to be triggered when they’re modified. For Example - having a property which maintains the state of the cache, when it’s changed, the application needs to update the values to UserDefaults. Something like this -

In this example, when isCacheUpdated and isUserDetailsUpdated are modified, it needs to save the values to UserDefaults to maintain the state of the cache. If you notice, the logic for updating the userDefaults is repetitive and not generic. So if we were to maintain some more states, we have to write more number of lines of code.

Same is the case with userData and accountData, when the data is updated, it needs to encrypt before saving it to database. How can we solve this problem where we can reuse this logic and make it more generic? And easy to use too 😃

The answer is Property Wrappers in Swift 5.1. Let’s see how it works and solves our problem.

Property Wrappers

Property wrappers are types which wraps a given value and attach associated logic to it. It can be implemented using either Struct or Class by annotating it with the @propertyWrapper attribute. The only real requirement is that each property wrapper type should contain a stored property called wrappedValue, which tells Swift which underlying value that’s being wrapped.

Let’s take the above example and see how we can use Property wrappers for isCacheUpdated and isUserDetailsUpdated -

In this example, we’ve created a property wrapper UserDefaultsBacked which wraps values which needs to be stored to UserDefaults. This struct is annotated with @propertyWrapper and wraps values of type DataType (Generic)

Property Wrappers can also have their own set of properties to hold some values. Here, we’ve a initialiser which takes key as a parameter to point to the correct data in userDefaults.

Now see how easy it is to use it in the code-

it’s that simple 😀 Just declare the variable with annotation and we can save significant amount code and make it more generic.

See the code below to implement Property Wrappers to wrap userData and accountData -

Here we create a property wrapper SecureData and implement the required property wrappedValue. See how we use this -

Just declare userData and accountData with @SecureData annotation and everything is set up. Swift automatically understands that userData and accountData are wrapped by property wrapper SecureData and it applies associated logic whenever these values are modified.

We’ve seen, property wrappers are easy to use types and saves significant amount of code and provide more generic solutions. It seems exciting to me but let me know what do you think about it.

Thanks for Reading 😀

--

--