Filter with Property Wrapper

Barış Uyar
DigiGeek
Published in
2 min readNov 8, 2022

Property wrapper is an extra layer that defines how a property is stored or computed on reading. It’s beneficial for replacing repetitive code found in getters and setters of properties.

You can create a Property Wrapper by defining a struct and marking it with the @propertyWrapper attribute. The attribute will require you to add a wrappedValue property to provide a return value on the implementation level.

Filter

We will try to implement the filter feature that we want to apply throughout the project, avoiding code duplication.

First, we created a protocol to be able to know according to which property of the model we will filter.

Our wrapper has three property. wrappedValue will store any array that conforms Filterable, filterString will set when we want to filter wrappedValue, filtered is a computed property that responsible for filter.

I will use Star Wars characters to make an example and filter them by both name and gender properties.

Our VC has two UI elements: text field to search and table view to list characters.

people array created as Filtered wrapper. We set an array which has five characters to wrappedValue of our property wrapper.

After each write or erase, filterString of wrapper will set and table view will reload.

Where we want to use our array, we will reach filtered array. In our example we reach for count and any people at any index.

In this example, we don’t need two arrays, one storing all characters and one storing filtered characters. If we need any filter feature in future, we will just conform our model to Filterable and create array as Filtered wrapper. Thanks for reading :)

--

--