Updated 26 August 2021
According to swift doc “A property wrapper adds a layer of separation between code that manages how a property is stored and the code that defines a property”. In another way, it encapsulates read and write access and provides additional behavior to property.
By using the property wrapper we can reuse the code by applying it to multiple properties. It can be use with class, structure, and enumeration. For better understanding, we will take an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
@propertyWrapper struct EmailValidationWrapper{ var email:String var wrappedValue:String{ get{ checkValidEmail(emai: email) ? email : "" }set{ self.email = newValue } } init(email:String) { self.email = email } func checkValidEmail(emai: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex) return (emailTest.evaluate(with: emai)) } } struct Employee { var name:String @EmailValidationWrapper var email:String func doFurther(){ if email == ""{ print("can not move further") }else{ print("proceed further") //Do things } } } |
1 2 3 4 5 |
let emp = Employee(name: "Test", email: EmailValidationWrapper(email: "testexample.com")) emp.doFurther() // Output can not move further emp1.doFurther() // proceed further |
In the above example, we have created a structure name EmailValidationWrapper which has @propertyWrapper attribute. Here you have to define a wrappedValue property unless you will get an error like “Property wrapper type ‘EmailValidationWrapper’ does not contain a non-static property named ‘wrappedValue'”.
We have created a emailValidator method name “checkValidEmail” from getter we are calling this method. We have created another structure named Employee and for email validation, we have used our structure “EmailValidationWrapper”. And by using the property wrapper we have created our maintenance code and can be use multiple times.
For details, understanding you can visit the swift doc. You can also check other blogs from here. if you have any issues or suggestions you can leave your query/suggestion in the comment section.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.