Last active
February 19, 2022 10:31
-
-
Save d-date/807f27ef494e23f030090e69a638ccc7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
guard let email = EmailAddress(rawValue: "[email protected]") 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