• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 7 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library for formatting strings on iOS and macOS

Travis Coveralls Swift 3.2 Swift 4.0 License Twitter

Sprinter

Introduction

What?

Sprinter is a library for Mac and iOS for formatting strings at runtime using the printf / NSLog format token conventions.

The aim is to provide a type-safe, Swift-friendly interface for string formatting that is fully compatible with the printf specification, as well as Apple's proprietary extensions for working with Objective-C data types.

The name "Sprinter" is derived from "String-Printer", just like the sprintf function in the C standard library.

Why?

Although Swift already offers string formatting support in the form of the String(format:arguments:) initializer, Swift's support is a fairly crude wrapper around the Objective-C API, and lacks support for some of the standard printf formatting features and data types. For example, there is no way to use the following format string in Swift:

"Hello %s, how are you?"

Because the %s token expects a C string (a pointer to a zero-terminated array of CChar), which the Swift String(format:arguments:) method won't accept. Instead, you must use the platform-specific %@ token instead, which limits reusability of strings between platforms.

Swift also provides no way to validate or inspect format strings. If the format contains a typo, or the format arguments don't match the ones in your code, the string will be displayed incorrectly at runtime, or worse, may crash or cause silent memory corruption.

Sprinter solves these issues by exposing the argument types for each format string, so you can write runtime validation logic and handle errors gracefully.

The Sprinter library could also be used as the basis for unit tests that validate your strings at build time, or even as part of a code generation pipeline to provide strongly-typed string properties and methods.

How?

Sprinter implements a robust string format parser based on the original IEEE printf spec along with Apple's additions for Objective-C. It makes use of Swift's string formatter internally, but performs pre-validation and type conversion of arguments to ensure that invalid types are never passed to the underlying implementation.

Sprinter includes a comprehensive test suite to ensure spec compliance, and output compatibility with Apple's formatter.

Usage

Installation

The entire Sprinter API is encapsulated in a single file, and everything public is prefixed or namespaced, so you can simply drag the Sprinter.swift file into your project to use it. If you prefer, there's a framework for Mac and iOS that you can import, or you can use CocoaPods, Carthage, or Swift Package Manager on Linux.

To install Sprinter using CocoaPods, add the following to your Podfile:

pod 'Sprinter', '~> 0.2.0'

Sprinter works with Swift 3.2 and 4.x and supports iOS 9 or macOS 10.0 and above

Integration

To format a string using Sprinter, you first create a FormatString instance, as follows:

let formatString = try FormatString("I have %i apples and %i bananas")

Note the try keyword - the FormatString initializer performs validation of the string, and will throw an error if the format is invalid. Once you have constructed the formatString object, you can use the print() method to output the formatted string. The print() method is variadic, which is convenient for passing arguments. There is also a second form that accepts a single array of arguments.

You would use the print() method as follows:

let string = try formatString.print(5, 6)
print(string) // I have 5 apples and 6 bananas

You'll notice that the print() function also requires try. This method will throw an error if the arguments you pass do not match the placeholders in the original format string. Errors thrown by either the FormatString initializer or the print() method will all be of type FormatString.Error, for example:

let formatString = try FormatString("I have %y apples") // throws FormatString.error.unexpectedToken("y")

let string = try FormatString("I have %i apples").print("foo") // throws FormatString.error.argumentMismatch(1, String.self, Int.self)

You can determine the required argument types before calling the print() method by using the types property of the FormatString, which returns an array of Swift Type values:

let types = formatString.types
print(types) // Int, Int

This is typically not useful at runtime (incorrect arguments would be a programming error that should be fixed before release), but it could be used in an automated test to verify that a given localized string key has the same argument types in each language.

Localization

The FormatString constructor also takes an optional locale argument, which can be used to localize the output:

let french = try FormatString("I have %i apples", locale: Locale(identifier: "fr-FR"))

This will affect how locale-specific formatting and punctuation is displayed, for example:

let english = try FormatString("%'g", locale: Locale(identifier: "en-US"))
try print(english.print(1234.56)) // 1,234.56

let french = try FormatString("%'g", locale: Locale(identifier: "fr-FR"))
try print(french.print(1234.56)) // 1 234,56

let german = try FormatString("%'g", locale: Locale(identifier: "de-DE"))
try print(german.print(1234.56)) // 1.234,56

Thread Safety

It is safe to create FormatString instances on a background thread.

Once created, a given FormatString instance is stateless, so the same instance can safely be used to print strings on multiple threads concurrently.

Advanced Usage

It may seem cumbersome to have to create a StringFormat object before printing, but it serves two purposes:

  1. It allows validation and type inspection of the string before the point of use. This means you can be confident that there will be no surprise errors when it is called.

  2. The expensive string parsing and NumberFormatter initialization steps can be performed once and then stored, not repeated each time the string is displayed.

For these reasons, it's recommended that you store and re-use your FormatString objects. You can either do this up-front for all strings, or lazily the first time each string is displayed - whichever makes more sense for your app.

A good approach would be to create a wrapper function that encapsulates your app-specific string requirements. For example, you might want to ignore string format errors in production (since it's too late to fix by that point), and just display a blank string instead. Here is an example wrapper that you might use in your app:

private var cache = [String: FormatString]()
private let queue = DispatchQueue(label: "com.Sprinter")

func localizedString(_ key: String, _ args: Any...) -> String {
    do {
        var formatString: FormatString?
        queue.sync { formatString = cache[key] }
        if formatString == nil {
            formatString = try FormatString(NSLocalizedString(key, comment: ""), locale: Locale.current)
            queue.async { cache[key] = formatString }
        }
        return try formatString?.print(arguments: args) ?? ""
    } catch {
        // Crash in development, but not in production
        assertionFailure("\(error)")
        return ""
    }
}

This function provides:

  • A convenient API for displaying keys from your Localizable.strings file
  • Encapsulated error handling, which will crash in development but fail gracefully in production
  • Thread-safe caching of FormatString instances for better performance

This is just an example approach, but it should work for most use cases.

More Repositories

1

iCarousel

A simple, highly customisable, data-driven 3D carousel for iOS and Mac OS
Objective-C
11,999
star
2

SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
Swift
7,781
star
3

FXBlurView

[DEPRECATED]
Objective-C
4,942
star
4

iRate

[DEPRECATED]
Objective-C
4,100
star
5

FXForms

[DEPRECATED]
Objective-C
2,926
star
6

SwipeView

SwipeView is a class designed to simplify the implementation of horizontal, paged scrolling views on iOS. It is based on a UIScrollView, but adds convenient functionality such as a UITableView-style dataSource/delegate interface for loading views dynamically, and efficient view loading, unloading and recycling.
Objective-C
2,646
star
7

layout

A declarative UI framework for iOS
Swift
2,231
star
8

iVersion

[DEPRECATED]
Objective-C
1,947
star
9

NullSafe

NullSafe is a simple category on NSNull that returns nil for unrecognised messages instead of throwing an exception
Objective-C
1,943
star
10

RetroRampage

Tutorial series demonstrating how to build a retro first-person shooter from scratch in Swift
Swift
1,486
star
11

XMLDictionary

[DEPRECATED]
Objective-C
1,139
star
12

AutoCoding

AutoCoding is a category on NSObject that provides automatic support for NSCoding and NSCopying to every object.
Objective-C
1,068
star
13

GZIP

A simple NSData category for gzipping/unzipping data in iOS and Mac OS
Objective-C
983
star
14

FastCoding

A faster and more flexible binary file format replacement for NSCoding, Property Lists and JSON
C
976
star
15

AsyncImageView

[DEPRECATED]
Objective-C
906
star
16

iConsole

[DEPRECATED]
Objective-C
859
star
17

Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
Swift
822
star
18

FXLabel

[DEPRECATED]
Objective-C
816
star
19

CountryPicker

CountryPicker is a custom UIPickerView subclass that provides an iOS control allowing a user to select a country from a list. It can optionally display a flag next to each country name, and the library includes a set of 249 high-quality, public domain flag images from FAMFAMFAM (http://www.famfamfam.com/lab/icons/flags/) that have been painstakingly re-named by country code to work with the library.
Objective-C
740
star
20

Euclid

A Swift library for creating and manipulating 3D geometry
Swift
637
star
21

SoundManager

Simple sound and music player class for playing audio on Mac and iPhone
Objective-C
630
star
22

FXImageView

FXImageView is a class designed to simplify the application of common visual effects such as reflections and drop-shadows to images, and also to help the performance of image loading by handling it on a background thread.
Objective-C
628
star
23

Base64

[DEPRECATED]
Objective-C
578
star
24

FXKeychain

[DEPRECATED]
Objective-C
554
star
25

MustOverride

Provides a macro that you can use to ensure that a method of an abstract base class *must* be overriden by its subclasses.
Objective-C
523
star
26

LayerSprites

LayerSprites is a library designed to simplify the use of sprite sheets (image maps containing multiple sub-images) in UIKit applications without using OpenGL or 3rd-party game libraries. Can load sprite sheets in the Coco2D format.
Objective-C
504
star
27

GLView

[DEPRECATED]
Objective-C
477
star
28

FXNotifications

An alternative API for NSNotificationCenter that doesn't suck
Objective-C
392
star
29

ShapeScript

The ShapeScript 3D modeling app for macOS and iOS
Swift
391
star
30

LRUCache

LRUCache is an open-source replacement for NSCache that behaves in a predictable, debuggable way
Swift
378
star
31

VectorMath

A Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based graphics
Swift
367
star
32

ReflectionView

[DEPRECATED]
Objective-C
359
star
33

Swiftenstein

Simple Wolfenstein 3D clone written in Swift
Swift
359
star
34

JPNG

JPNG is a bespoke image file format that combines the compression benefits of JPEG with the alpha channel support of a PNG file. The JPNG library provides an Objective-C implementation of this format along with transparent JPNG loading support for iOS and Mac OS.
Objective-C
340
star
35

StandardPaths

StandardPaths is a category on NSFileManager for simplifying access to standard application directories on iOS and Mac OS and abstracting the iCloud backup flags on iOS. It also provides support for working with device-specific file suffixes, such as the @2x suffix for Retina displays, or the -568h suffix for iPhone 5 and can optionally swizzle certain UIKit methods to support these suffixes more consistently.
Objective-C
336
star
36

ViewUtils

ViewUtils is a collection of category methods designed that extend UIView with all the handy little properties and functionality that you always wished were built-in to begin with.
Objective-C
324
star
37

FXPageControl

Simple, drop-in replacement for the iPhone UIPageControl that allows customisation of the dot colour, size and spacing.
Objective-C
298
star
38

BaseModel

BaseModel provides a base class for building model objects for your iOS or Mac OS projects. It saves you the hassle of writing boilerplate code, and encourages good practices by reducing the incentive to cut corners in your model implementation.
Objective-C
288
star
39

OrderedDictionary

This library provides OrderedDictionary and MutableOrderedDictionary subclasses.
Objective-C
278
star
40

ColorUtils

[DEPRECATED]
Objective-C
256
star
41

Tribute

A command-line tool for tracking Swift project licenses
Swift
246
star
42

OSNavigationController

[DEPRECATED]
Objective-C
233
star
43

Consumer

Mac and iOS library for parsing structured text
Swift
226
star
44

iNotify

[DEPRECATED]
Objective-C
225
star
45

FPSControls

An experimental implementation of touch-friendly first-person shooter controls using SceneKit and Swift
Swift
215
star
46

OSCache

OSCache is an open-source re-implementation of NSCache that behaves in a predictable, debuggable way.
Objective-C
200
star
47

Chess

A simple Chess game for iOS, written in Swift
Swift
177
star
48

RequestQueue

[DEPRECATED]
Objective-C
174
star
49

FXReachability

Lightweight reachability class for Mac and iOS
Objective-C
173
star
50

CryptoCoding

CryptoCoding is a superset of the NSCoding protocol that allows for simple, seamless AES encryption of any NSCoding-compatible object.
Objective-C
148
star
51

RequestUtils

A collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa.
Objective-C
142
star
52

CubeController

CubeController is a UIViewController subclass that can be used to create a rotating 3D cube navigation.
Objective-C
142
star
53

HTMLLabel

[DEPRECATED]
Objective-C
139
star
54

NSOperationStack

[DEPRECATED]
Objective-C
118
star
55

SVGPath

Cross-platform Swift library for parsing SVGPath strings
Swift
111
star
56

HRCoder

HRCoder is a replacement for the NSKeyedArchiver and NSKeyedUnarchiver classes that uses a human-readable/editable format that can easily be stored in a regular Plist or JSON file.
Objective-C
104
star
57

iPrompt

[DEPRECATED]
Objective-C
99
star
58

Presentations

Code samples and projects for presentations that I have given
Objective-C
98
star
59

FXPhotoEditView

[DEPRECATED]
Objective-C
92
star
60

StackView

StackView is a class designed to simplify the implementation of vertical stacks of views on iOS. You can think of it as a bit like a simplified version of UITableView.
Objective-C
73
star
61

WebContentView

[DEPRECATED]
Objective-C
69
star
62

StringCoding

StringCoding is a simple Mac/iOS library for setting object properties of any type using string values. It can automatically detect the property type and attempt to interpret the string as the right kind of value. It's particularly oriented towards iOS app theming (see README for details).
Objective-C
57
star
63

ArrayUtils

[DEPRECATED]
Objective-C
49
star
64

Swune

Swift/UIKit reimplementation of the Dune II RTS game
Swift
46
star
65

Parsing

Supporting code for my talk entitled "Parsing Formal Languages with Swift"
Swift
42
star
66

MACAddress

[DEPRECATED]
Objective-C
39
star
67

FXParser

[DEPRECATED]
Objective-C
34
star
68

RotateView

Objective-C
34
star
69

RandomSequence

A class for creating independent, repeatable pseudorandom number sequences on Mac and iOS
Objective-C
28
star
70

FloatyBalloon

This is the source code for a simple game called Floaty Balloon, based on the gameplay of Flappy Bird. It was created as a tutorial for http://iosdevelopertips.com
Objective-C
25
star
71

Concurrency

Full source code for a simple currency calculator app
Objective-C
15
star
72

FXJSON

[DEPRECATED]
Objective-C
15
star
73

PNGvsJPEG

This is a simple benchmark app to compare JPEG vs PNG loading performance on iOS. Spoiler: JPEG wins.
Objective-C
6
star