Recall & Review
beginner
What is a property wrapper in Swift?
A property wrapper is a Swift feature that lets you add extra behavior to properties, like validation or formatting, by wrapping the property’s value with custom code.
Click to reveal answer
intermediate
How do you define a custom validation property wrapper?
You create a struct or class with the @propertyWrapper attribute, include a wrappedValue property, and add validation logic inside the setter of wrappedValue.Click to reveal answer
intermediate
What happens if a value fails validation in a custom property wrapper?
You can handle it by rejecting the value, setting a default, throwing an error, or logging a message, depending on how you design the wrapper.
Click to reveal answer
beginner
Show a simple example of a custom validation property wrapper that ensures a string is not empty.
@propertyWrapper
struct NonEmpty {
private var value: String
init(wrappedValue: String) {
self.value = wrappedValue.isEmpty ? "Default" : wrappedValue
}
var wrappedValue: String {
get { value }
set { value = newValue.isEmpty ? "Default" : newValue }
}
}
struct User {
@NonEmpty var name: String
}
Click to reveal answer
beginner
Why use custom validation property wrappers instead of validating manually?
They keep your code clean by centralizing validation logic, reduce repeated code, and make properties safer and easier to maintain.
Click to reveal answer
What keyword do you use to mark a custom property wrapper in Swift?
✗ Incorrect
The correct keyword to define a property wrapper is @propertyWrapper.
Where do you put the validation logic inside a custom property wrapper?
✗ Incorrect
Validation logic is usually placed inside the setter of wrappedValue to check or modify new values.
What does the wrappedValue property represent in a property wrapper?
✗ Incorrect
wrappedValue holds the actual value that the property wrapper manages.
If you want to provide a default value when validation fails, where do you do it?
✗ Incorrect
You provide default values or fallback logic inside the setter of wrappedValue when validation fails.
Which of these is NOT a benefit of using custom validation property wrappers?
✗ Incorrect
Property wrappers help with validation but do not automatically fix all bugs.
Explain how to create a custom validation property wrapper in Swift and why it is useful.
Think about how you can check or change values when they are set.
You got /4 concepts.
Describe a simple example of a custom validation property wrapper that ensures a string is never empty.
Imagine you want to avoid empty names in a user profile.
You got /4 concepts.