Skip to content

Instantly share code, notes, and snippets.

@alobaili
Last active November 30, 2020 17:01
Show Gist options
  • Save alobaili/47d0e22df48c1c0259beb57c6337f0cc to your computer and use it in GitHub Desktop.
Save alobaili/47d0e22df48c1c0259beb57c6337f0cc to your computer and use it in GitHub Desktop.
Correct the locale of numeric digits of an address string generated from CNPostalAddressFormatter
import Foundation
extension String {
/// Corrects the numeric digits of user-facing strings so that
/// they appear in the correct locale of the device.
///
/// For example, `CNPostalAddressFormatter` does not take into consideration the locale when
/// converting numerics digits. An address `"1234 King Fahd Rd."` in "en_US" locale gets
/// converted to `"1234 طريق الملك فهد"` in "ar_SA" while it should be `"١٢٣٤ طريق الملك فهد"`.
/// Another example is when you get a user facing string from a webservice and you want to make
/// sure the numbers in the string are in the correct locale.
/// - Returns: The same string after correcting the numbers locale.
func correctingNumbersWithCurrentLocale() -> String {
let formatter = NumberFormatter()
var string = ""
for character in self {
if let number = formatter.number(from: String(character)) {
string += formatter.string(from: number)!
} else {
string += String(character)
}
}
return string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment