Skip to content

Instantly share code, notes, and snippets.

@harlanhaskins
Created July 8, 2015 17:29
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 harlanhaskins/330500289a44079c7222 to your computer and use it in GitHub Desktop.
Save harlanhaskins/330500289a44079c7222 to your computer and use it in GitHub Desktop.
String.stringByFormattingPhoneNumbers()
extension String {
static let phoneDetector = NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue, error: nil)!
func stringByFormattingPhoneNumbers() -> String {
var mutableString = self
String.phoneDetector.enumerateMatchesInString(self, options: NSMatchingOptions.allZeros, range: NSRange(location: 0, length: count(self))) { result, flags, stop in
if let
range = self.rangeFromNSRange(result.range),
phoneNumber = result.phoneNumber.flatMap(PhoneManager.sanitizedPhoneNumber) {
mutableString.replaceRange(range, with: PhoneManager.formattedPhoneNumber(phoneNumber))
}
}
return mutableString
}
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
if let
from = String.Index(self.utf16.startIndex + nsRange.location, within: self),
to = String.Index(self.utf16.startIndex + nsRange.location + nsRange.length, within: self) {
return from ..< to
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment