Q.1 What is Property Wrapper?
Ans. In Swift, PropertyWrapper is a feature that allows you to add extra behavior to properties by defining a custom type and using it to wrap the property’s value.
It helps you manage repetitive logic, such as validation, default values, or transformation, in a clean and reusable way.
To make it a property wrapper, mark it with the @propertyWrapper attribute, which must have a property named wrappedValue
.
This wrappedValue
property is where the actual value, wrapped by the property wrapper, is stored.
Property wrappers were introduced in Swift 5.1
Q.2 How to define a Property Wrapper?
Ans. We have to take care of two requirements for a property wrapper type
1- We define the property wrapper using the @propertyWrapper
attribute.
2- It must have a wrappedValue property which is a computed property.
Example-1 Write a wrapper for the capitalized first character.
Let’s implement Property Wrapper in five easy steps–
Step-1 We create a new struct called Capital
struct Capital { var value: String }
Step-2 We annotate the struct with @propertyWrapper
@propertyWrapper struct Capital { var value: String }
Step-3 We implement wrappedValue
with our business logic
@propertyWrapper struct Capital { var value: String var wrappedValue: String { get { value.capitalized } set { value = newValue } } }
Step- 4 We implement an initializer
@propertyWrapper struct Capital { var value: String var wrappedValue: String { get { value.capitalized } set { value = newValue } } init(wrappedValue: String) { self.value = wrappedValue } }
Step -5 we will use our property wrapper Capital
struct User { @Capital var firstName: String @Capital var lastName: String var address: String } let user = User(firstName: "shivi", lastName: "tiwari", address: "varanasi") print(user.firstName) print(user.lastName) print(user.address)
Output:-
Shivi
Tiwari
varanasi
Explanation:-
In the code, we have defined a property wrapper Capital
that capitalizes the value it wraps.
We have also defined a User struct with properties firstName
, lastName
, and address
. The firstName
and lastName
properties use the @Capital
property wrapper to automatically capitalize the values assigned to them.
As we can see, when we create a User
instance and assign values to firstName
and lastName
, the @Capital property
wrapper automatically capitalizes the values, ensuring that the first letter of each word is in uppercase. The address property is not using the @Capital
property wrapper, so its value remains unchanged.
Read More:
Property Wrapper Official Doc
Top iOS Interview Questions and Answers