我正在尝试将此工作目标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
}
matches
数组正确匹配输入的电话号码,并正确显示类型,如下所示:
但是检查结果类型时我的if
语句总是返回false
if match.resultType == NSTextCheckingType.PhoneNumber
输入测试为555-555-5555或5558881234
那么,我该如何正确检查NSTextCheckingType?
答案 0 :(得分:2)
试试这个:
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)
}
}
我希望这对你有所帮助。