Formatting strings is one of the most common tasks in building software. It's usually not that complex, but it can be tempting to cut corners.

When working with things like currency or street addresses, having a robust formatting system in place can be crucial in ensuring our app works well all over the world.

Today we'll look at Format, a library from Roy Marmelstein that can help us achieve all this with ease.

Format starts by extending Swift's number types to add a format function. We can call this on any number (even literals) and it will return a String with our desired format:

134 . format ( Decimals . Two ) // => "134.00"

Format makes localizing a breeze. It uses the device's current locale by default, or we can render a specific one:

let gb = NSLocale ( localeIdentifier : "GB" ) 87 . format ( Currency . GBP , locale : gb ) // => "£ 87.00"

Ordinal numbers can really help class up the joint:

134 . format ( General . Ordinal ) // => "134th"

Format can format in all sorts of interesting ways, for example:

10.11 . format ( General . SpellOut ) // => "ten point one one"

Numbers are cool, but what about addresses? Almost every nation has a slightly different convention for how they format street addresses.

Format wraps CNPostalAddressFormatter from the Contacts framework (Bite #24) to make formatting addresses quite simple:

AddressFormatter () . format ( "1 Infinite Loop" , city : "Cupertino" , state : "CA" , postalCode : "95014" , country : "USA" , ISOCountryCode : "US" ) // => "1 Infinite Loop

Cupertino CA 95014

USA"

Format also extends CLPlacemark, adding a function to format that class's addressDictionary property. Users expect things to look familiar. Never underestimate the power of good localization.

More info about Format can be found at git.io/format