0
0
Swiftprogramming~5 mins

@propertyWrapper declaration in Swift

Choose your learning style9 modes available
Introduction

The @propertyWrapper lets you create a reusable way to add extra behavior to variables. It helps keep your code clean and organized.

When you want to add validation to a variable automatically.
When you want to add default behavior to many variables without repeating code.
When you want to log or track changes to a variable.
When you want to control how a variable is stored or accessed.
When you want to share common logic for variables across your app.
Syntax
Swift
@propertyWrapper
struct WrapperName {
    private var value: Type

    var wrappedValue: Type {
        get { value }
        set { value = newValue }
    }

    init(wrappedValue initialValue: Type) {
        self.value = initialValue
    }
}

The wrappedValue property is required. It controls how the variable behaves.

The init(wrappedValue:) lets you set a default value when using the wrapper.

Examples
This wrapper capitalizes any string assigned to the variable.
Swift
@propertyWrapper
struct Capitalized {
    private var value: String = ""

    var wrappedValue: String {
        get { value }
        set { value = newValue.capitalized }
    }

    init(wrappedValue: String) {
        self.value = wrappedValue.capitalized
    }
}
This wrapper keeps an integer within a set range.
Swift
@propertyWrapper
struct Clamped {
    private var value: Int
    private let range: ClosedRange<Int>

    var wrappedValue: Int {
        get { value }
        set { value = min(max(newValue, range.lowerBound), range.upperBound) }
    }

    init(wrappedValue: Int, _ range: ClosedRange<Int>) {
        self.range = range
        self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
    }
}
Sample Program

This program shows how the @Capitalized property wrapper automatically capitalizes the name when setting it.

Swift
import Foundation

@propertyWrapper
struct Capitalized {
    private var value: String = ""

    var wrappedValue: String {
        get { value }
        set { value = newValue.capitalized }
    }

    init(wrappedValue: String) {
        self.value = wrappedValue.capitalized
    }
}

struct Person {
    @Capitalized var name: String
}

var person = Person(name: "john doe")
print(person.name)  // Prints "John Doe"
person.name = "jane smith"
print(person.name)  // Prints "Jane Smith"
OutputSuccess
Important Notes

You can add extra properties or methods inside your property wrapper to support more features.

Property wrappers can be used on variables in structs, classes, and enums.

Remember to use @propertyWrapper before your wrapper struct or class.

Summary

@propertyWrapper helps add reusable behavior to variables.

It requires a wrappedValue property to control the variable.

You use it by adding @YourWrapperName before a variable.