Create Property Wrapper in Swift

Needone App
1 min readDec 19, 2022

--

In Swift, property wrappers are a language feature that allows you to wrap a piece of code around a property, in order to add additional behavior or functionality to that property. Property wrappers are defined using the @ symbol, followed by the name of the property wrapper.

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:

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.

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
}
}

Originally published at https://needone.app on December 19, 2022.

👉 If you want received more stories like this, please follow my channel to get the latest update in time

--

--

No responses yet