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 regex:NSRegularExpression = try NSRegularExpression(pattern: "^1[3|4|5|7|8][0-9]{9}$", options: .caseInsensitive)

            let result:NSTextCheckingResult = regex.firstMatch(in: self, options:.reportProgress, range: NSMakeRange(0, self.count))!

            if result != nil {

                return true

            }

        }catch { }

        

        return false


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM