How do I create custom property wrappers in Swift?

In Swift, custom property wrappers are a powerful feature that allows you to encapsulate and reuse code that implements property behaviors. A property wrapper is defined by creating a struct or class that wraps a value, providing additional functionality in terms of storage, validation, or transformation.

Creating a Custom Property Wrapper

To create a custom property wrapper, use the `@propertyWrapper` attribute followed by defining a struct or class. You'll typically need a wrapped value and optional logic to handle get, set, and initialization of that value.

Example of a Custom Property Wrapper

@propertyWrapper struct Uppercase { var wrappedValue: String { didSet { wrappedValue = wrappedValue.uppercased() } } init(wrappedValue: String) { self.wrappedValue = wrappedValue.uppercased() } } struct Example { @Uppercase var name: String init(name: String) { self.name = name } } let example = Example(name: "john doe") print(example.name) // Output: JOHN DOE

Swift property wrapper custom property wrapper Swift programming encapsulation reusable code