Property wrappers encapsulate get/set logic behind attribute syntax—@State, @Published, and @AppStorage in SwiftUI build on this language feature.
Custom wrapper sketch
@propertyWrapper
struct Clamped {
private var value: Int
let range: ClosedRange<Int>
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
}
Playground note
SwiftUI property wrappers need the SwiftUI framework—this lesson demonstrates the language mechanism with plain structs and print().
Important interview questions and answers
- Q: What problem do property wrappers solve?
A: Reusable storage and access patterns without repeating boilerplate getters/setters—validation, persistence, threading. - Q: projectedValue ($)?
A: Some wrappers expose a projected value—e.g.$bindingfor two-way SwiftUI bindings.
Self-check
- What attribute declares a property wrapper type?
- Why are SwiftUI wrappers not used in sandbox code?
Tip: SwiftUI wrappers like @State build on property wrappers—explore locally in Xcode.
Interview prep
- Problem solved?
Reusable get/set logic without repeating boilerplate.
- projectedValue?
Some wrappers expose $ syntax—e.g. SwiftUI bindings.