create a property wrapper in swift

To create a property wrapper in Swift, you can use the @propertyWrapper attribute. A property wrapper is a generic struct that wraps a value and provides additional behavior around access to that value.

Here's an example of a property wrapper that validates a string:

main.swift
@propertyWrapper
struct ValidatedString {
    var value: String = ""
    
    var wrappedValue: String {
        get { return value }
        set {
            if newValue.contains(" ") {
                print("Invalid value - contains whitespace")
            } else {
                value = newValue
            }
        }
    }
}
335 chars
16 lines

This property wrapper has an underlying String value and provides validation logic in the setter. Whenever a new value is assigned to the wrapped value, it checks to make sure there are no spaces in the string. If there are, it prints an error message.

You can use the property wrapper like this:

main.swift
struct User {
    @ValidatedString var username: String
    @ValidatedString var password: String
}
100 chars
5 lines

In this example, the User struct has two properties with the @ValidatedString attribute. Anytime a value is assigned to these properties, the property wrapper's validation logic will run.

gistlibby LogSnag