Discover Property Wrappers in Swift


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


You’ve heard that Property Wrappers are a very powerful feature of Swift, but you're not entirely sure how they work? 🤨

Don’t worry! I’ve got you covered! 😌

In just a few paragraphs I’ll explain everything you need to understand how to use a Property Wrapper!

Let’s start with this piece of code:

As you can see, I’ve made the mistake of adding an extra white space at the end of the URL!

And this small mistake actually has big consequences: because of it my URL is not considered valid 😞

That’s frustrating because such small mistakes can happen very easily, especially if our app fetches URLs from a remote configuration service.

So wouldn’t it be nice if we had a mechanism to wrap our property around some logic that would always trim any extra whitespaces?

As you can imagine, this is where a Property Wrapper comes into play!

So let’s implement a Property Wrapper in 5 easy steps!

Step 1️⃣, we create a new struct called Trimmed:

Step 2️⃣, we annotate that struct with @propertyWrapper:

Step 3️⃣, we implement a wrappedValue with our business logic:

Step 4️⃣, we implement an initializer:

Step 5️⃣, we use our new Property Wrapper:

And that’s it, we’ve covered the basics of how a Property Wrapper works in Swift 🥳

Thanks to this feature, we are able to easily wrap a property around a layer of business logic that’s guaranteed to be called whenever we use the property 👌

Here’s the code if you want to experiment with it!

@propertyWrapper
struct Trimmed {
    var string: String

    init(wrappedValue: String) {
        self.string = wrappedValue
    }

    var wrappedValue: String {
        get {
            string.trimmingCharacters(
                in: .whitespacesAndNewlines
            )
        }
        set {
            string = newValue
        }
    }
}

import Foundation

struct API {
    @Trimmed var url: String
}

var api = API(url: "https://myapi.com/ ")

URL(string: api.url) // valid URL ✅
Previous
Previous

Discover Generics in Swift

Next
Next

5 Things You Didn’t Know About KeyPaths