`stringWithFormat:` for the sophisticated hacker set

Related tags

Text FormatterKit
Overview

FormatterKit

This library is no longer being maintained. Since its initial release in 2011, Apple has filled in many of the gaps FormatterKit was created to fill in Foundation and other SDK frameworks:

Deprecated FormatterKit API Apple SDK API Availability
TTTAddressFormatter CNPostalAddressFormatter iOS 9.0+ / macOS 10.11+
TTTArrayFormatter NSListFormatter iOS 13.0+ / macOS 10.15+
TTTNameFormatter NSPersonNameComponentsFormatter iOS 9.0+ / macOS 10.11+
TTTLocationFormatter NSMeasurementFormatter + NSUnitDistance / NSUnitAngle iOS 10.0+ / macOS 10.12+
TTTOrdinalNumberFormatter NSNumberFormatter + NSNumberFormatterOrdinalStyle iOS 9.0+ / macOS 10.11+
TTTTimeIntervalFormatter NSRelativeDateTimeFormatter iOS 13.0+ / macOS 10.15+
TTTUnitOfInformationFormatter NSMeasurementFormatter + NSUnitInformationStorage iOS 13.0+ / macOS 10.15+

You can continue to use FormatterKit in your projects, but we recommend switching to the corresponding Apple APIs as soon as it makes sense to do so.

Going forward, we plan to spin out non-deprecated formatters into their own repositories for future development as well as any new projects. This repository will remain archived here for compatibility with existing installations.


FormatterKit is a collection of well-crafted NSFormatter subclasses for things like units of information, distance, and relative time intervals. Each formatter abstracts away the complex business logic of their respective domain, so that you can focus on the more important aspects of your application.

In short, use this library if you're manually formatting any of the following (with string interpolation or the like):

  • Addresses: Create formatted address strings from components (e.g. 221b Baker St / Paddington / Greater London / NW1 6XE / United Kingdom )
  • Arrays: Display NSArray elements in a comma-delimited list (e.g. "Russell, Spinoza & Rawls")
  • Colors: RGB, CMYK, and HSL your ROY G. BIV in style. (e.g. #BADF00D, rgb(255, 100, 42))
  • Location, Distance & Direction: Show CLLocationDistance, CLLocationDirection, and CLLocationSpeed in metric or imperial units (eg. "240ft Northwest" / "45 km/h SE")
  • Names: Display personal names in the correct format, according to the current locale and source language (eg. "山田花子" for the Japanese first name "花子" (Hanako) and last name "山田" (Yamada))
  • Ordinal Numbers: Convert cardinal NSNumber objects to their ordinal in most major languages (eg. "1st, 2nd, 3rd" / "1ère, 2ème, 3ème")
  • Time Intervals: Show relative time distance between any two NSDate objects (e.g. "3 minutes ago" / "yesterday")
  • Units of Information: Humanized representations of quantities of bits and bytes (e.g. "2.7 MB")
  • URL Requests: Print out cURL or Wget command equivalents for any NSURLRequest (e.g. curl -X POST "https://www.example.com/" -H "Accept: text/html")

Installation

CocoaPods

You can install FormatterKit via CocoaPods, by adding the following line to your Podfile:

pod 'FormatterKit', '~> 1.9.0'

Run the pod install command to download the library and integrate it into your Xcode project.

Carthage

To use FormatterKit in your Xcode project using Carthage, specify it in Cartfile:

github "FormatterKit/FormatterKit" ~> 1.9.0

Then run the carthage update command to build the framework, and drag the built FormatterKit.framework into your Xcode project.

Demo

Build and run the FormatterKit Example project in Xcode to see an inventory of the available FormatterKit components.


TTTAddressFormatter

Address formats vary greatly across different regions. TTTAddressFormatter ties into the Address Book frameworks to help your users find their place in the world.

For example, addresses in the United States take the form:

Street Address
City State ZIP
Country

Whereas addresses in Japan follow a different convention:

Postal Code
Prefecture Municipality
Street Address
Country

Requires that the AddressBook and AddressBookUI frameworks are linked with #import statements in Prefix.pch. TTTAddressFormatter isn't available on OS X.

Example Usage

TTTAddressFormatter *addressFormatter = [[TTTAddressFormatter alloc] init];
NSLog(@"%@", [addressFormatter stringFromAddressWithStreet:street locality:locality region:region postalCode:postalCode country:country]);

TTTArrayFormatter

Think of this as a production-ready alternative to NSArray -componentsJoinedByString:. TTTArrayFormatter comes with internationalization baked-in and provides a concise API that allows you to configure for any edge cases.

Example Usage

NSArray *list = [NSArray arrayWithObjects:@"Russel", @"Spinoza", @"Rawls", nil];
TTTArrayFormatter *arrayFormatter = [[TTTArrayFormatter alloc] init];
[arrayFormatter setUsesAbbreviatedConjunction:YES]; // Use '&' instead of 'and'
[arrayFormatter setUsesSerialDelimiter:NO]; // Omit Oxford Comma
NSLog(@"%@", [arrayFormatter stringFromArray:list]); // # => "Russell, Spinoza & Rawls"

TTTColorFormatter

RGB, CMYK, and HSL your ROY G. BIV in style. TTTColorFormatter provides string representations of colors.

Example Usage

TTTColorFormatter *colorFormatter = [[TTTColorFormatter alloc] init];
NSString *RGB = [colorFormatter RGBStringFromColor:[UIColor orangeColor]];

TTTLocationFormatter

When working with CoreLocation, you can use your favorite unit for distance... so long as your favorite unit is the meter. If you want to take distance calculations and display them to the user, you may want to use kilometers instead --- or maybe even miles if you're of the Imperial persuasion.

TTTLocationFormatter gives you a lot of flexibility in the display of coordinates, distances, direction, speed, and velocity. Choose Metric or Imperial, cardinal directions, abbreviations, or degrees, and configure everything else (number of significant digits, etc.) with the associated NSNumberFormatter.

Example Usage

TTTLocationFormatter *locationFormatter = [[TTTLocationFormatter alloc] init];
CLLocation *austin = [[CLLocation alloc] initWithLatitude:30.2669444 longitude:-97.7427778];
CLLocation *pittsburgh = [[CLLocation alloc] initWithLatitude:40.4405556 longitude:-79.9961111];

Distance in Metric Units with Cardinal Directions

NSLog(@"%@", [locationFormatter stringFromDistanceAndBearingFromLocation:pittsburgh toLocation:austin]);
// "2,000 km Southwest"

Distance in Imperial Units with Cardinal Direction Abbreviations

[locationFormatter.numberFormatter setMaximumSignificantDigits:4];
[locationFormatter setBearingStyle:TTTBearingAbbreviationWordStyle];
[locationFormatter setUnitSystem:TTTImperialSystem];
NSLog(@"%@", [locationFormatter stringFromDistanceAndBearingFromLocation:pittsburgh toLocation:austin]);
// "1,218 miles SW"

Speed in Imperial Units with Bearing in Degrees

[locationFormatter setBearingStyle:TTTBearingNumericStyle];
NSLog(@"%@ at %@", [locationFormatter stringFromSpeed:25],[locationFormatter stringFromBearingFromLocation:pittsburgh toLocation:austin]);
// "25 mph at 310°"

Coordinates

[locationFormatter.numberFormatter setUsesSignificantDigits:NO];
NSLog(@"%@", [locationFormatter stringFromLocation:austin]);
// (30.2669444, -97.7427778)

TTTNameFormatter

TTTNameFormatter formats names according to the internationalization standards of the AddressBook framework, which determine, for example, the display order of names and whether or not to delimit components with whitespace.

TTTNameFormatter isn't available on OS X.

Example Usage

TTTNameFormatter *nameFormatter = [[TTTNameFormatter alloc] init];
NSString *frenchName = [nameFormatter stringFromPrefix:nil firstName:@"Guillaume" middleName:@"François" lastName:@"Antoine" suffix:@"Marquis de l'Hôpital"];
NSLog(@"%@", frenchName);
// "Guillaume François Antoine Marquis de l'Hôpital"

NSString *japaneseName = [nameFormatter stringFromFirstName:@"孝和" lastName:@""];
NSLog(@"%@", japaneseName);
// "関孝和"

TTTOrdinalNumberFormatter

NSNumberFormatter is great for Cardinal numbers (17, 42, 69, etc.), but it doesn't have built-in support for Ordinal numbers (1st, 2nd, 3rd, etc.)

A naïve implementation might be as simple as throwing the one's place in a switch statement and appending "-st", "-nd", etc. But what if you want to support French, which appends "-er", "-ère", and "-eme" in various contexts? How about Spanish? Japanese?

TTTOrdinalNumberFormatter supports English, Spanish, French, German, Irish, Italian, Japanese, Dutch, Portuguese, Simplified Chinese and Swedish. For other languages, you can use the standard default, or override it with your own. For languages whose ordinal indicator depends upon the grammatical properties of the predicate, TTTOrdinalNumberFormatter can format according to a specified gender and/or plurality.

Example Usage

TTTOrdinalNumberFormatter *ordinalNumberFormatter = [[TTTOrdinalNumberFormatter alloc] init];
[ordinalNumberFormatter setLocale:[NSLocale currentLocale]];
[ordinalNumberFormatter setGrammaticalGender:TTTOrdinalNumberFormatterMaleGender];
NSNumber *number = [NSNumber numberWithInteger:2];
NSLog(@"%@", [NSString stringWithFormat:NSLocalizedString(@"You came in %@ place!", nil), [ordinalNumberFormatter stringFromNumber:number]]);

Assuming you've provided localized strings for "You came in %@ place!", the output would be:

  • English: "You came in 2nd place!"
  • French: "Vous êtes arrivé à la 2e place !"
  • Spanish: "Usted llegó en 2.o lugar!"

TTTTimeIntervalFormatter

Nearly every application works with time in some way or another. And when we display temporal information to users, it's typically in relative terms to the present, like "3 minutes ago", "10 months ago", or "last month". TTTTimeIntervalFormatter defaults to a smart, relative display of an NSTimeInterval value, with options to extend that behavior to your particular use case.

Example Usage

TTTTimeIntervalFormatter *timeIntervalFormatter = [[TTTTimeIntervalFormatter alloc] init];
[timeIntervalFormatter stringForTimeInterval:0]; // "just now"
[timeIntervalFormatter stringForTimeInterval:-100]; // "1 minute ago"
[timeIntervalFormatter stringForTimeInterval:-8000]; // "2 hours ago"

// Turn idiomatic deictic expressions on / off
[timeIntervalFormatter stringForTimeInterval:-100000]; // "1 day ago"
[timeIntervalFormatter setUsesIdiomaticDeicticExpressions:YES];
[timeIntervalFormatter stringForTimeInterval:-100000]; // "yesterday"

// Customize the present tense deictic expression for
[timeIntervalFormatter setPresentDeicticExpression:@"seconds ago"];
[timeIntervalFormatter stringForTimeInterval:0]; // "seconds ago"

// Expand the time interval for present tense
[timeIntervalFormatter stringForTimeInterval:-3]; // "3 seconds ago"
[timeIntervalFormatter setPresentTimeIntervalMargin:10];
[timeIntervalFormatter stringForTimeInterval:-3]; // "seconds ago"

TTTUnitOfInformationFormatter

No matter how far abstracted from its underlying hardware an application may be, there comes a day when it has to communicate the size of a file to the user. TTTUnitOfInformationFormatter transforms a number of bits or bytes into a humanized representation, using either SI decimal or IEC binary unit prefixes.

Example Usage

TTTUnitOfInformationFormatter *unitOfInformationFormatter = [[TTTUnitOfInformationFormatter alloc] init];
[unitOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:416]]; // "56 bytes"

// Display in either bits or bytes
[unitOfInformationFormatter setDisplaysInTermsOfBytes:NO];
[unitOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:416]]; // "416 bits"

// Use IEC Binary prefixes (base 2 rather than SI base 10; see http://en.wikipedia.org/wiki/IEC_60027)
[unitOfInformationFormatter setUsesIECBinaryPrefixesForCalculation:NO];
[unitOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:8660]]; // "8.66 Kbit"

[unitOfInformationFormatter setUsesIECBinaryPrefixesForCalculation:YES];
[unitOfInformationFormatter setUsesIECBinaryPrefixesForDisplay:YES];
[unitOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:416]]; // "8.46 Kibit"

TTTURLRequestFormatter

NSURLRequest objects encapsulate all of the information made in a network request, including url, headers, body, etc. This isn't something you'd normally want to show to a user, but it'd be nice to have a way to make it more portable for debugging. Enter: TTTURLRequestFormatter. In addition to formatting requests simply as POST http://www.example.com/, it also generates cURL and Wget commands with all of its headers and data fields intact to debug in the console.

Example Usage

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.example.com/"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"text/html" forHTTPHeaderField:@"Accept"];
[TTTURLRequestFormatter cURLCommandFromURLRequest:request];
curl -X POST "https://www.example.com/" -H "Accept: text/html"

Localizations

FormatterKit comes fully internationalized, with .strings files for the following locales:

  • Catalan (ca)
  • Chinese (Simplified) (zh_Hans)
  • Chinese (Traditional) (zh_Hant)
  • Czech (cs)
  • Danish (da)
  • Dutch (nl)
  • English (en)
  • French (fr)
  • German (de)
  • Greek (el)
  • Hebrew (he)
  • Hungarian (hu)
  • Indonesian (id)
  • Italian (it)
  • Korean (ko)
  • Norwegian Bokmål (nb)
  • Norwegian Nynorsk (nn)
  • Polish (pl)
  • Portuguese (Brazilian) (pt_BR)
  • Russian (ru)
  • Spanish (es)
  • Swedish (sv)
  • Turkish (tr)
  • Ukranian (uk)
  • Vietnamese (vi)

License

FormatterKit is available under the MIT license. See the LICENSE file for more info.

You might also like...
A Hacker News client written in React Native
A Hacker News client written in React Native

React Native Hacker News A modern cross-platform HackerNews client built on React Native Features The app currently has the following functionality: H

HackerWeb 2: A read-only Hacker News client.
HackerWeb 2: A read-only Hacker News client.

HackerWeb 2 A read-only Hacker News client. Only 30 front-page stories. No more no less. Revolutionary comments thread UI. Smart collapse and easy nav

Hackers is an elegant iOS app for reading Hacker News written in Swift.
Hackers is an elegant iOS app for reading Hacker News written in Swift.

Hackers Hackers is an iPhone and iPad app for reading Hacker News on the go. It's optimised for quickly catching up on the latest news and comments wi

A Hacker News reader iOS app written in Swift.
A Hacker News reader iOS app written in Swift.

HackerNews A Hacker News reader iOS app written in Swift. Features View "top", "newest", and "show" posts from Hacker News. Read posts using the SFSaf

This was built during my bootcamp using SwiftUI, WebKit and an API from Hacker News

HackerNewsReader This was built during my bootcamp using SwiftUI, WebKit and an API from Hacker News. This was programmed from scratch with SwiftUI. I

Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.
Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.

TheAnimation TheAnimation is Type-safe CAAnimation wrapper. Introduction For example, if you want to animate backgroundColor with CABasicAnimation, yo

Swiftline is a set of tools to help you create command line applications
Swiftline is a set of tools to help you create command line applications

Swiftline is a set of tools to help you create command line applications. Swiftline is inspired by highline Swiftline contains the following: Colorize

A complete set of primitives for concurrency and reactive programming on Swift
A complete set of primitives for concurrency and reactive programming on Swift

A complete set of primitives for concurrency and reactive programming on Swift 1.4.0 is the latest and greatest, but only for Swift 4.2 and 5.0 use 1.

📱AutoLayout can be set differently for each device
📱AutoLayout can be set differently for each device

DeviceLayout DeviceLayout is a Swift framework that lets you set Auto Layout constraints's differently for each device Using only IBInspector of Xcode

A set of protocols for Arithmetic, Statistics and Logical operations

Arithmosophi - Arithmosoϕ Arithmosophi is a set of missing protocols that simplify arithmetic and statistics on generic objects or functions. As Equat

A simple OAuth library for iOS with a built-in set of providers
A simple OAuth library for iOS with a built-in set of providers

SwiftyOAuth is a small OAuth library with a built-in set of providers and a nice API to add your owns. let instagram: Provider = .instagram(clientID:

Swift-friendly API for a set of powerful Objective C runtime functions.
Swift-friendly API for a set of powerful Objective C runtime functions.

ObjectiveKit ObjectiveKit provides a Swift friendly API for a set of powerful Objective C runtime functions. Usage To use ObjectiveKit: Import Objecti

A set of tools to trim, crop and select frames inside a video

PryntTrimmerView A set of tools written in swift to crop and trim videos. Example To run the example project, clone the repo, and run pod install from

Lightweight library to set an Image as text background. Written in swift.
Lightweight library to set an Image as text background. Written in swift.

Simple and light weight UIView that animate text with an image.

CHIPageControl is a set of cool animated page controls to replace boring UIPageControl.
CHIPageControl is a set of cool animated page controls to replace boring UIPageControl.

CHIPageControl is a set of cool animated page controls to replace boring UIPageControl. We were inspired by Jardson Almeida dribbble sh

A fully customizable container view controller to display a set of ViewControllers in a horizontal scroll view. Written in Swift.
A fully customizable container view controller to display a set of ViewControllers in a horizontal scroll view. Written in Swift.

DTPagerController This is a control for iOS written in Swift. DTPagerController is simple to use and easy to customize. Screenshots Default segmented

CHIOTPField is a set of textfields that can be used for One-time passwords, SMS codes, PIN codes, etc. Mady by @ChiliLabs - https://chililabs.io
CHIOTPField is a set of textfields that can be used for One-time passwords, SMS codes, PIN codes, etc. Mady by @ChiliLabs - https://chililabs.io

CHIOTPField CHIOTPField is a set of textfields that can be used for One-time passwords, SMS codes, PIN codes, etc. All fields support insertion of one

A simple OAuth library for iOS with a built-in set of providers
A simple OAuth library for iOS with a built-in set of providers

SwiftyOAuth is a small OAuth library with a built-in set of providers and a nice API to add your owns. let instagram: Provider = .instagram(clientID:

Handy Combine extensions on NSObject, including Set<AnyCancellable>.
Handy Combine extensions on NSObject, including SetAnyCancellable.

Storable Description If you're using Combine, you've probably encountered the following code more than a few times. class Object: NSObject { var c

Owner
Mattt
GitHub engineer working on Dependabot
Mattt
A set of libraries to help users find and replace native system emojis with EmojiOne in their app or website.

This repository is now maintained as JoyPixels/emoji-toolkit. You'll find the latest version of our resources at emoji-toolkit. Please see the UPGRADE

JoyPixels Inc. 4.5k Dec 24, 2022
The Amazing Audio Engine is a sophisticated framework for iOS audio applications, built so you don't have to.

Important Notice: The Amazing Audio Engine has been retired. See the announcement here The Amazing Audio Engine The Amazing Audio Engine is a sophisti

null 523 Nov 12, 2022
Cross-platform, sophisticated frontend for the libretro API.

RetroArch is the reference frontend for the libretro API. Popular examples of implementations for this API includes video game system emulators and game engines as well as more generalized 3D programs. These programs are instantiated as dynamic libraries. We refer to these as "libretro cores".

null 7.4k Dec 27, 2022
The Effects Library allows developers to create sophisticated and realistic particle systems such as snow, fire, rain, confetti, fireworks, and smoke with no or minimal effort.

The Effects Library allows developers to create sophisticated and realistic particle systems such as snow, fire, rain, confetti, fireworks, and smoke with no or minimal effort.

Stream 182 Jan 6, 2023
A beautiful set of predefined colors and a set of color methods to make your iOS/OSX development life easier.

Installation Drag the included Colours.h and Colours.m files into your project. They are located in the top-level directory. You can see a demo of how

Ben Gordon 3.1k Dec 28, 2022
Hacker News client for macOS

HNReaderApp This is the public repository for the HNReader macOS application. You can report any issue and suggest/request new features in the issue s

Mattia Righetti 186 Oct 14, 2022
A Hacker News reader in Swift

SwiftHN A Hacker News reader in Swift using the best features of both the language and iOS 8 latest API (well, that's the end goal) SwiftHN is now ava

Thomas Ricouard 1.7k Dec 24, 2022
App that shows recently posted articles about Android or iOS on Hacker News

App that shows recently posted articles about Android or iOS on Hacker News

Jose Moffa 0 Nov 9, 2021
A simple Hacker News mobile client

A simple Hacker News mobile client. Overview This app was built with the Hacker News API This is one of my first apps outside of a tut

Antonio Vega Ochoa 0 Nov 29, 2021
A small, read-only app for Hacker News.

Hacker News Reader Available on the App Store This is a simple Hacker News front-page reader that I cooked up because I didn't like any existing solut

Ryan Nystrom 259 Dec 11, 2022