Skip to Content
Course content

42: Building a Custom Property Wrapper

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a PR from a junior developer who had built a settings screen for a complex productivity app. I noticed their SettingsManager class was absolutely bloated. For every single user preference—theme, notification toggle, sync interval—they had written a manual getter and setter that interfaced with UserDefaults. It was about 100 lines of repetitive boilerplate: get { return UserDefaults.standard.string(forKey: "theme") ?? "light" } and so on. It wasn't "wrong," but it was tedious to read and a nightmare to maintain. If they wanted to change how they stored data, they had to touch twenty different properties.

This is exactly the kind of friction that Property Wrappers were designed to eliminate. Instead of writing the same logic over and over inside your properties, you encapsulate that logic into a separate structure. Once defined, you can apply that logic to any property with a single attribute, like @UserDefault. It effectively separates the storage logic from the business logic of your class.

Designing the WrappedValue Interface

To create a property wrapper, you define a struct or class and mark it with the @propertyWrapper attribute. The only hard requirement is that your type must implement a property called wrappedValue. This is the magic hook; whenever you access the property in your main class, Swift redirects that call to the wrappedValue of your wrapper.

Let's fix that SettingsManager problem. I usually start by making the wrapper generic so it can handle Strings, Bools, or Integers without needing separate wrappers for each type. Here is how I'd build it:

@propertyWrapper
struct UserDefault<T> {
    let key: String
    let defaultValue: T

    var wrappedValue: T {
        get {
            return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

Notice that I'm using a generic T. I personally find it much cleaner to pass the defaultValue into the initializer. That way, the property wrapper doesn't have to guess what a "sane" default is for every different setting in your app.

Applying the Wrapper to Your Models

Once the wrapper is defined, using it is incredibly clean. You no longer need to write explicit getters and setters in your manager class. You just declare the property and tag it. Swift handles the initialization of the UserDefault struct behind the scenes.

class SettingsManager {
    @UserDefault(key: "app_theme", defaultValue: "system")
    var theme: String

    @UserDefault(key: "notifications_enabled", defaultValue: true)
    var isNotificationsEnabled: Bool
    
    @UserDefault(key: "sync_interval", defaultValue: 3600)
    var syncInterval: Int
}

When you call manager.theme = "dark", Swift isn't actually assigning "dark" to a simple string. It's calling the set block of our UserDefault wrapper, which in turn updates UserDefaults. I love this pattern because if I later decide to move my settings from UserDefaults to a database or a JSON file, I only have to change the code in one place—the wrapper—and the rest of my app remains completely untouched.

One quick tip: remember that property wrappers are initialized when the containing object is created. If your wrapper needs to do something heavy, be mindful of where you're placing these properties. But for most use cases, like validation or persistence, they are an absolute game-changer for keeping your codebase lean.




📋 Practical Task

Building a ClampedNumeric Property Wrapper

In many apps, you have numeric values that must stay within a specific range (for example, a volume slider from 0 to 100, or a zoom level from 1.0 to 5.0). Instead of writing if value > max { value = max } every time you update a variable, you can automate this.

Your Task: Create a property wrapper called @Clamped that takes a minValue and a maxValue. Any value assigned to a property wrapped with @Clamped should be automatically constrained to that range. If a value is set below the minimum, it should be set to the minimum; if it's above the maximum, it should be set to the maximum.

  • Define the @propertyWrapper struct Clamped.
  • Use a generic type T that conforms to Comparable and Numeric.
  • Implement the wrappedValue logic to handle the clamping in the set block.
  • Test your wrapper by creating a PlayerSettings class with a volume property clamped between 0 and 100, and try assigning 150 to it to ensure it caps at 100.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.