WrappedValue and projectedValue help you control how a property behaves and what extra information it can provide.
WrappedValue and projectedValue in Swift
@propertyWrapper struct WrapperName { var wrappedValue: Type var projectedValue: ExtraType init(wrappedValue: Type) { self.wrappedValue = wrappedValue self.projectedValue = ... // set extra info } }
wrappedValue is the main value the property holds.
projectedValue is extra info you can access with a $ prefix.
@propertyWrapper struct Capitalized { private var value: String = "" var wrappedValue: String { get { value } set { value = newValue.capitalized } } init(wrappedValue: String) { self.wrappedValue = wrappedValue } }
@propertyWrapper struct Logged { var wrappedValue: Int { didSet { print("Value changed to \(wrappedValue)") } } init(wrappedValue: Int) { self.wrappedValue = wrappedValue } }
projectedValue.@propertyWrapper struct Toggle { var wrappedValue: Bool var projectedValue: String { wrappedValue ? "On" : "Off" } init(wrappedValue: Bool) { self.wrappedValue = wrappedValue } }
This program uses a property wrapper Trimmed that removes spaces around a string. The projectedValue gives the length of the trimmed string. We create a user with spaces around the name, then print the trimmed name and its length.
import Foundation @propertyWrapper struct Trimmed { private var value: String = "" var wrappedValue: String { get { value } set { value = newValue.trimmingCharacters(in: .whitespacesAndNewlines) } } var projectedValue: Int { value.count } init(wrappedValue: String) { self.wrappedValue = wrappedValue } } struct User { @Trimmed var name: String } var user = User(name: " Alice ") print("Name: '\(user.name)'" ) print("Length: \(user.$name)")
You access wrappedValue normally, but projectedValue with a $ before the property name.
Property wrappers make your code cleaner by reusing common property logic.
Not all property wrappers need a projectedValue, but it is useful for extra info.
wrappedValue is the main value stored or controlled by the property wrapper.
projectedValue is extra information or behavior you can access with $property.
Use these to add helpful features to your properties without repeating code.