Created
July 8, 2015 17:29
-
-
Save harlanhaskins/330500289a44079c7222 to your computer and use it in GitHub Desktop.
String.stringByFormattingPhoneNumbers()
This file contains 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
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