swift 報錯 Call can throw, but it is not marked with 'try' and the error is not handled
在開發中使用正則表示式時報了這樣的問題:Call can throw, but it is not marked with 'try' and the error is not handled,即:
let regex:NSRegularExpression = NSRegularExpression(pattern: "^1[3|4|5|7|8][0-9]{9}$", options: .caseInsensitive)
先看下在OC中的使用
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^1[3|4|5|7|8][0-9]{9}$" options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
if (result) {
return YES;
}
return NO;
對比一下發現原因是沒有新增錯誤處理,可以通過新增try解決。
最終解決後代碼:
do{
let
let result:NSTextCheckingResult = regex.firstMatch(in: self, options:.reportProgress, range: NSMakeRange(0, self.count))!
if
return true
}
}catch { }
return false