Skip to content

Instantly share code, notes, and snippets.

@d-date
Last active February 19, 2022 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-date/807f27ef494e23f030090e69a638ccc7 to your computer and use it in GitHub Desktop.
Save d-date/807f27ef494e23f030090e69a638ccc7 to your computer and use it in GitHub Desktop.
import Foundation
struct EmailAddress: RawRepresentable, Codable {
let rawValue: String
init?(rawValue: String) {
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let range = NSRange(rawValue.startIndex..<rawValue.endIndex,in: rawValue)
let matches = detector?.matches(in: rawValue, options: [], range: range)
guard let match = matches?.first, matches?.count == 1 else { return nil }
guard match.url?.scheme == "mailto", match.range == range else { return nil }
self.rawValue = rawValue
}
}
guard let email = EmailAddress(rawValue: "example@gmail.com") else {
fatalError("not email address")
}
print(email)
guard let notEmail = EmailAddress.init(rawValue: "https://google.com") else {
throw URLError(.badURL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment