— Swift, Property Wrapper — 1 min read
Property wrappers are a powerful feature in Swift that allow you to define a piece of reusable code that can modify the behavior of a property. In this post, we will create a custom property wrapper that converts a string to lowercase.
To define our custom property wrapper, we need to use the @propertyWrapper attribute. The @propertyWrapper attribute indicates that we are defining a new property wrapper.
1@propertyWrapper2struct Lowercased {3    private var value: String4    5    init(wrappedValue: String) {6        self.value = wrappedValue.lowercased()7    }8    9    var wrappedValue: String {10        get { value }11        set { value = newValue.lowercased() }12    }13}In this example, we defined a new property wrapper called Lowercased. This property wrapper has a single property called value, which is a string. We also defined an initializer, which takes a string and sets the value property to the lowercase version of the input string. Finally, we defined a computed property called wrappedValue, which gets and sets the value of the value property.
Now that we have defined our custom property wrapper, we can use it on any property with a string type. Here's an example:
1struct Person {2    @Lowercased var firstName: String3    @Lowercased var lastName: String4}5
6let person = Person(firstName: "John", lastName: "SMITH")7print(person.firstName) // prints "john"8print(person.lastName) // prints "smith"9
10person.firstName = "JANE"11print(person.firstName) // prints "jane"In this example, we defined a Person struct with two properties: firstName and lastName. Both properties are decorated with the @Lowercased property wrapper. When we instantiate a new Person object, the input strings are automatically converted to lowercase.
In conclusion, we learned how to create a custom property wrapper in Swift that converts a string to lowercase. Property wrappers are a powerful tool that can help you write more concise and reusable code. I hope this post was helpful in understanding how to create your own custom property wrappers.