I am trying to convert this Objective-C working code to Swift ( which is based on this Apple documentation )
-(BOOL)validatePhone:(NSString*)phone {
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber
error:&error];
NSArray *matches = [detector matchesInString:phone
options:0
range:NSMakeRange(0, [phone length])];
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypePhoneNumber) {
NSString *phoneNumber = [match phoneNumber];
self.inputPhoneNumber.text = phoneNumber;
return TRUE;
}
}
NSLog(@"Phone Number Not Found");
return FALSE;
}
Here is my quick conversion:
func validatePhone(phone: NSString) -> Bool {
var error: NSError?
let detector = NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue, error: &error)
var matches: NSArray = [detector!.matchesInString(phone as String, options: nil, range: NSMakeRange(0, phone.length))]
var match:NSTextCheckingResult
for match in matches{
if match.resultType == NSTextCheckingType.PhoneNumber{
inputPhoneNumber.text = match.phoneNumber
return true
}
}
NSLog("Phone Number Not Found")
return false
}
The array matchescorrectly matches the entered phone number and correctly displays the type, as shown below:

But my operator ifalways returns false when checking the type of result
if match.resultType == NSTextCheckingType.PhoneNumber
Entrance tested as 555-555-5555 or 5558881234
So, how should I check for NSTextCheckingType correctly?
source
share