我试图将这个工作目标C代码转换为
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;
}
这是我的Swift转换:
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
}
匹配数组正确匹配输入的电话号码并正确显示类型,如下所示:
但是在检查结果类型时我的if语句总是返回false
if match.resultType == NSTextCheckingType.PhoneNumber
输入测试为555-555-5555或5558881234
那么,我该如何正确检查NSTextCheckingType?
最佳答案 试试这个:
var text = "555-555-5555"
let types: NSTextCheckingType = .PhoneNumber
var error : NSError?
let detector = NSDataDetector(types: types.rawValue, error: &error)
var matches = detector!.matchesInString(text, options: nil, range: NSMakeRange(0, count(text)))
for match in matches {
println(match.phoneNumber!)
}
在上面的代码中,您不需要检查resultType,因为它只在与电话号码匹配时进入循环.
但是,否则,如果要匹配多个类型,如下例所示:
var text = "http://www.example.com"
let types: NSTextCheckingType = .PhoneNumber | .Link
var error : NSError?
let detector = NSDataDetector(types: types.rawValue, error: &error)
var matches = detector!.matchesInString(text, options: nil, range: NSMakeRange(0, count(text)))
您可以使用以下代码检查是否匹配:
for match in matches {
if let phone = match.phoneNumber! {
println(phone)
}
if let url = match.URL! {
println(url)
}
}
我希望这对你有帮助.