Understanding Property Wrappers in Swift

Batikan Sosun
Dev Genius
Published in
3 min readOct 2, 2021

--

Photo by Rudy Dong on Unsplash

We were already familiar with the @ “at sign” in Objective-C. Then we were using @IBAction, @NSCopying, @UIApplicationMain examples in Swift language, and we thought it would be limited to these.

As time passed, Swift began to increase the use of @ prefixed attribute.

By way of the SwiftUI announcement, we realized that this @ prefix will be used more often, and will be in the future of the Swift language.
Example: @State, @Binding, @EnvironmentObject.

However, these prefixes started to be used not only with SwiftUI but also outside of it. Example: @propertyWrapper

What is the property wrapper?

Essentially, a property wrapper is a type that wraps in a given value in order to bind additional logic to it.

It can be implemented using both a struct or a class by @propertyWrapper.

You can find here SE-0258 the background of the motivation of the property wrapper.

Now, imagine that you have a boilerplate code like below.

I assume you realize that you need to write boilerplate code every time you need to apply this pattern. This is the problem that creates code redundant.

As I said before, a property wrapper is nothing more than a struct or class annotated with the @propertyWrapper attribute and property with name wrappedValue.

As the name implies, the wrappedValue property holds the value that’s wrapped by the @propertyWrapper.

Let’s start a practice with an example.

I will create a property wrapper with the name Capitalized, and that will capitalize the value.

Now let’s go back to our boilerplate code, and re-create that with the Capitalized property wrapper.

As you see, @propertyWrapper saves you from complex and redundant code. This is just a simple example that applies a capitalized property wrapper.

Don’t constraint with that you can also use in another case.

- Use property wrapper for validating a condition that requires an e-mail.
- Use a property wrapper that stores data with UserDefault.
- Use a property wrapper that limits the score.

I’m going to list some useful third-party property wrappers that will help you.

BetterCodable

Level up your Codable structs through property wrappers. The goal of these property wrappers is to avoid implementing a custom init(from decoder: Decoder) throws and suffer through boilerplate.

Burritos

A collection of Swift Property Wrappers (formerly “Property Delegates”)

ValidatedPropertyKit

ValidatedPropertyKit enables you to easily validate your properties with the power of Property Wrappers.

Secure Property Storage

Helps you define secure storage for your properties using Swift property wrappers.

Thank you for reading. Don’t forget to applaud :)

--

--

Tweeting tips and tricks about #swift #xcode #apple Twitter @batikansosun Weekly Swift Blogging