Custom validation property wrappers help you check and control the values stored in properties easily and clearly.
0
0
Custom validation property wrappers in Swift
Introduction
When you want to make sure a user's input meets certain rules before saving it.
When you want to keep your code clean by reusing validation logic for many properties.
When you want to automatically reject or fix wrong values in your data.
When you want to add clear error messages or feedback for invalid data.
When you want to separate validation rules from your main code for better organization.
Syntax
Swift
@propertyWrapper struct ValidationName { private var value: Type var wrappedValue: Type { get { value } set { // validation logic here if isValid(newValue) { value = newValue } else { // handle invalid value } } } init(wrappedValue initialValue: Type) { // validate initial value if isValid(initialValue) { self.value = initialValue } else { // handle invalid initial value self.value = defaultValue } } private func isValid(_ value: Type) -> Bool { // return true if value is valid return true } }
The @propertyWrapper keyword defines a wrapper around a property.
The wrappedValue is the actual property value with validation logic inside the setter.
Examples
This wrapper makes sure a string is never empty. If empty, it sets a default string.
Swift
@propertyWrapper struct NonEmpty { private var value: String = "" var wrappedValue: String { get { value } set { value = newValue.isEmpty ? "Default" : newValue } } init(wrappedValue: String) { self.wrappedValue = wrappedValue } }
This wrapper ensures an integer is always positive. If a negative or zero is set, it resets to 1.
Swift
@propertyWrapper struct Positive { private var value: Int = 1 var wrappedValue: Int { get { value } set { value = newValue > 0 ? newValue : 1 } } init(wrappedValue: Int) { self.wrappedValue = wrappedValue } }
Sample Program
This program uses a custom property wrapper @NonEmpty to make sure the user's name is never empty. If you try to set it empty, it changes to "Default" automatically.
Swift
import Foundation @propertyWrapper struct NonEmpty { private var value: String = "" var wrappedValue: String { get { value } set { value = newValue.isEmpty ? "Default" : newValue } } init(wrappedValue: String) { self.wrappedValue = wrappedValue } } struct User { @NonEmpty var name: String } var user = User(name: "") print("User name is: \(user.name)") user.name = "Alice" print("User name is: \(user.name)") user.name = "" print("User name is: \(user.name)")
OutputSuccess
Important Notes
Property wrappers can add validation without repeating code everywhere.
Use init(wrappedValue:) to validate the initial value when the property is created.
Remember to handle invalid values gracefully to avoid crashes.
Summary
Custom validation property wrappers help keep your data clean and safe.
They let you reuse validation rules easily across your code.
They make your code easier to read by separating validation from main logic.