Localizing numbers, date, time and names in iOS / Swift

Here is a list of techniques I use to present values to international users in iOS.

Numbers

// Float
String.localizedStringWithFormat("%.3f", M_PI)
// 3.142

// Integer
String.localizedStringWithFormat("%i", 12_345)
// 12,345

Currencies

let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.string(from: 99.95)
// $99.95

Date and time

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
dateFormatter.string(from: Date())
// 8/1/15, 6:12 PM

Date and time using template

This technique can be used if you need to have more control on date and time formatting.

let dateFormatterTemplate = DateFormatter()
dateFormatterTemplate.setLocalizedDateFormatFromTemplate("yyyyMMMMdjjmmss")
dateFormatterTemplate.string(from: Date())
// August 1, 2015, 6:12:05 PM

Mass

let massFormatter = MassFormatter()
massFormatter.unitStyle = .long
massFormatter.string(fromKilograms: 1.5)
// 1.5 kilograms

Distance

let lengthFormatter = LengthFormatter()
lengthFormatter.unitStyle = .long
lengthFormatter.string(fromValue: 100, unit: .meter)
// 900 meters

Personal names

var nameComponents = PersonNameComponents()
nameComponents.givenName = "Brian"
nameComponents.middleName = "Edward"
nameComponents.familyName = "Cox"

let nameFormatter = PersonNameComponentsFormatter()
nameFormatter.style = .medium
nameFormatter.string(from: nameComponents)
// Brian Cox

Reference







Wooooow!