Property wrapper in Swift
- Property wrapper is the Swift language feature that allows us to define a custom type, that implements behavior from get and set methods, and reuse it everywhere.
- Declare
@propertyWrapper
keyword before we declare the type that we want to use as property wrapper. It can bestruct
,class
, orenum
.
- We are required to implement the
wrappedValue
property. Most of the time we declare customsetter
andgetter
in this property. This property can be acomputed
orstored
property.
Example of @Properywrapper
@propertyWrapper
struct Capitalized {
private(set) var text: String = "" //Declared to store the value
var wrappedValue: String {
get { return text }
set { text = newValue.uppercased() }
}
}
//Now use it
struct User{
@Capitalized var userName: String
}
var user = User()
user.userName = "Pawan"
print(user.userName) //PAWAN
Thanks for reading, Happy Coding 👨💻