In our first chapter on Property wrappers we saw some SwiftUI native examples that not only allow you to encapsulate functionality that's commonly associated with properties, like @State
, but they also allow you to add custom behaviors to properties without duplicating code.
Today we are going to explore how to write our custom Property wrappers to improve readability and maintainability.
Defining A Property Wrapper
@propertyWrapper
attribute and can apply it to properties in a class, struct, or enum. The core requirement for a property wrapper is a wrappedValue
property that provides the underlying value.
Let's start with a basic example: a property wrapper that logs changes to a property whenever its value is modified.
@propertyWrapper
struct Validator { // 1
private var value: String
init(wrappedValue: String) { // 2
self.value = wrappedValue
}
var wrappedValue: String {
get { value }
set {
print("Email changed from \"\(value)\" to \"\(newValue)\"") // 3
value = newValue
}
}
}
struct User { // 4
@Validator var email: String
}
var user = User(email: "test")
user.email = "test@educaswift.com"
// Prints: Value changed from "test" to "test@educaswift.com"
Continue reading
Access to all the content with our plans.
- Junior level content
- Senior level content
- Expert level content
- Extra content
- Question submissions
Monthly
Yearly
Be the first to comment