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  keyword before we declare the type that we want to use as property wrapper. It can be , or .
  • We are required to implement the  property. Most of the time we declare custom  and  in this property. This property can be a  or  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 ðŸ‘¨‍💻

Popular posts from this blog

Frame vs bounds in Swift

DateFomatter in Swift