Create Property Wrapper in Swift

· 1 min read
Create Property Wrapper in Swift

What is Property Wrapper

Property wrapper are a language feature that allows you to wrap a piece of code around a property in Swift world, which can help us to add additional behavior or functionality to that property. The benefits of it is to reduce the code repetition.

Property wrapper is defined using the @ symbol, followed by the name of the property wrapper. It is not something magic, here's an example of a simple property wrapper called Trimmed that trims leading and trailing whitespace from a string:

@propertyWrapper
struct Trimmed {
    private(set) var wrappedValue: String

    init(wrappedValue: String) {
        self.wrappedValue = wrappedValue.trimmingCharacters(in: .whitespaces)
    }
}

You can use this property wrapper by applying it to a property like this:

struct Person {
	@Trimmed var name: String
}

let person = Person(name: " First Name, Last Name ")
print(person.name)
// output:
//First Name, Last Name

Property wrappers are a useful tool for adding functionality to properties in a concise and reusable way. They are often used for things like value validation, data formatting, and thread synchronization.

Common property wrappers

As you may observed already, there are some existing property wrappers which we already talked in the previous articles:

Test property wrapper

To test above property wrapper:

import XCTest

class TrimmedTests: XCTestCase {
    func testTrimmed() {
        let person = Person(name: "  John Smith   ")
        XCTAssertEqual(person.name, "John Smith")
    }
    
    struct MockPerson {
        @Trimmed var name: String
    }
}