Property wrappers in Swift

@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)
}
}
@QRValidator
var strValue: String?
  1. 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.
  2. 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store