Swift Property Wrappers: Simplifying Codebase

Mukhammadjon Tokhirov
Stackademic
Published in
2 min readMar 3, 2024

--

In Swift programming, simplicity is the key. That’s where property wrappers come in. Imagine making your code easier to read and understand. That’s what property wrappers do in Swift. They help tidy up your code effortlessly. Let’s explore how they make coding simpler. In this article, we’ll uncover the power of property wrappers in simplifying data management and enhancing your Swift development experience.

Let’s consider a scenario where we want to enforce a maximum limit for a property. We’ll explore two approaches: one using a property wrapper and the other without.

Example 1: Using property wrapper
In this approach, we’ll use a property wrapper called @limitTop to enforce a maximum limit of 10 for the value property. The property wrapper abstracts away the logic for enforcing the limit, resulting in cleaner and more concise code.

struct Test {
@limitTop(limit: 10)
var value: Int = 0
}

Example 2: Without property wrapper
Alternatively, we can achieve the same functionality without using a property wrapper. In this approach, we rely on the didSet observer to check if the value exceeds the limit and manually reset it if necessary. While this approach works, it results in more verbose code with additional boilerplate logic.

struct Test {
// Define a property named value with didSet observer to enforce the limit
var value: Int = 0 {
didSet {
// Check if the value exceeds the limit and reset it if necessary
if value > 10 {
value = 10
}
}
}
}

So, where did this@limitTop come from?
That was @propertyWrapper that we discussed earlier .

Here’s how this magic is created

@propertyWrapper
struct limitTop {
private var value: Int = 0
private let limit: Int

var wrappedValue: Int {
get { return value }
set {
value = min(newValue, limit)
}
}

init(limit: Int) {
self.limit = limit
}
}

So property wrappers allows us to wrap and modify any stored property — utlilizing an@propertyWrapper- marked type, and annotations matching the name of that type.

In conclusion, while there are numerous discussions and articles covering property wrappers, the primary objective here was to underscore their vital role in our projects. Through the examples and explanations provided, we’ve highlighted how property wrappers offer a streamlined approach to managing data in Swift, enhancing code readability and maintainability. By leveraging property wrappers, developers can simplify complex tasks and unlock new possibilities in Swift development.

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--