1. I've read what an NSPredicate is but I still dont understand exactly what it does
NSPredicate is a sort of Expression object and sort of a family member of NSExpression. Both classes implement an Expression Language which has its own syntax and semantics. NSPredicate returns boolean value, and NSExpression returns value of arbitrary types, when evaluated with a given object.
You may have read this aleady, but you should check this if you want to use NSPredicate or NSExpression in your app.
Predicate Programming Guide
Anyway, there are many articles about NSPredicate and you may have read some of them and still asks I still dont understand exactly what it does, that cannot be a good question as readers get no clue what's in your mind. Please try to explain what you understand and what you do not understand.
2. ... If I only use MATCHES, I get an error, what does the SELF mean here, is it similar to the way we use self.text = ....
You do not write something like `if == 0 { ... }` in your Swift code, no?
In Swift, `==` is a binary operator which claims operands on both hand sides.
Even when human readers can easily guess the left hand side, you need to specify it explicitly.
In the Expression Language used in NSPredicate or NSExpression, MATCHES is a binary operator and the left hand side operand is required.
I wrote NSPredicate returns boolean value when evaluated with a given object.
In your example code, when you use the predicate as `emailPredicate.evaluate(with: self.text)`, SELF represents `self.text`.
Your can write the same thing like this:
let emailPredicate = NSPredicate(format:"text MATCHES %@", emailRegularExpression)
if emailPredicate.evaluate(with: self) { //<- giving `self` instead of `self.text`
//...
} else {
//...
}
In this code, text in "text MATCHES %@" represents the `text` property of the given object `self`.
But I would not use NSPredicate as in your example. For example you can write something like this:
func validateEmailTextField() {
let emailRegularExpression = "^[A-Z0-9a-z.-_]+@[A-Z0-9a-z-_.]+\\.[A-Za-z]{2,6}$" //^ and $ needed
if
let text = self.text,
text.range(of: emailRegularExpression, options: .regularExpression) != nil
{
//...
} else {
//...
}
}
Or I would use NSRegularExpression explicitly.