Property wrappers in Swift
As the name goes, property wrappers in swift is a type that wraps the value with additional logic to it apart from just read and write.
Implementing this is quite easy and also leverages your code reusability. Your struct or class can be annotated with the @propertyWrapper attribute. Each property wrapper should contain a wrappedValue, which tells the value that's being wrapped.
Let’s look at an example to validate a string.
@propertyWrapper
struct QRValidator {
private var value: String? init(wrappedValue value: String?) {
self.value = value
}var wrappedValue: String? {
get {
return validate(qr: value) ? value : nil
}
set {
value = newValue
}
}
private func validate(qr: String?) -> Bool {
guard let qr = qr, !qr.isEmpty else { return false }
let pattern = "^(CH-QR##).+(##CH-QR)$"
let regex = try? NSRegularExpression(pattern: pattern, options: []) return (qr.range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil)
}
}
To define the wrapped property in the code:
@QRValidator
var strValue: String?
All we have to do is mark the property with the annotation @. The property type must match the wrappedValue type of wrapper.
Although property wrappers are super helpful in hiding the code and making the code more reuseable there are a few limitations.
- Error handling is not supported yet, we cannot mark the getter and setter as throws. Say for example you are validating an email and the user enters an invalid email and you try to set that, all we can do is return nil.
- You cannot combine multiple wrappers. For instance, if you want to check for numbers in your string and validate for the case sensitivity, two wrappers in one would create an error as you are applying the first property wrapper on the value of the second property wrapper.
That’s all!😊 Drop in your suggestion if any.