I have written this function in String Extension and can't figure out the error.
func isEmail() -> Bool {
let regex = NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: [.CaseInsensitive])
return regex.firstMatchInString(self, options: nil, range: NSMakeRange(0, characters.count)) != nil
}
The error is:
Call can throw, but it is not marked with 'try' and the error is not handled
NSRegularExpression(pattern:)
throws an error if the pattern is invalid. In your case, the pattern is fixed, so an invalid pattern would be a programming error.This is a use-case for the "forced-try" expression with
try!
:try!
disables the error propagation so that the method does not throw an error (which the caller has to catch). It will abort with a runtime exception if the pattern is invalid, which helps to find programming errors early.Note also that
NSRange()
counts the length ofNSString
, i.e. the number of UTF-16 code points, socharacters.count
should beutf16.count
, otherwise it might crash e.g. with Emoji characters.