{"id":2054,"url":"https://github.com/nicklockwood/Sprinter","last_synced_at":"2025-08-06T14:32:57.682Z","repository":{"id":56922191,"uuid":"111731961","full_name":"nicklockwood/Sprinter","owner":"nicklockwood","description":"A library for formatting strings on iOS and macOS","archived":false,"fork":false,"pushed_at":"2018-02-09T18:25:23.000Z","size":34,"stargazers_count":166,"open_issues_count":1,"forks_count":9,"subscribers_count":8,"default_branch":"master","last_synced_at":"2024-12-04T02:41:52.015Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nicklockwood.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-22T21:01:40.000Z","updated_at":"2023-09-13T14:50:15.000Z","dependencies_parsed_at":"2022-08-21T04:50:20.216Z","dependency_job_id":null,"html_url":"https://github.com/nicklockwood/Sprinter","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklockwood%2FSprinter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklockwood%2FSprinter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklockwood%2FSprinter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklockwood%2FSprinter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nicklockwood","download_url":"https://codeload.github.com/nicklockwood/Sprinter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228915452,"owners_count":17991406,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-01-05T20:16:02.297Z","updated_at":"2024-12-09T15:30:48.755Z","avatar_url":"https://github.com/nicklockwood.png","language":"Swift","funding_links":[],"categories":["Libs","Text","Swift","Text [🔝](#readme)"],"sub_categories":["Text","Other free courses","Other Testing","Keychain"],"readme":"[![Travis](https://img.shields.io/travis/nicklockwood/Sprinter.svg)](https://travis-ci.org/nicklockwood/Sprinter)\n[![Coveralls](https://coveralls.io/repos/github/nicklockwood/Sprinter/badge.svg)](https://coveralls.io/github/nicklockwood/Sprinter)\n[![Swift 3.2](https://img.shields.io/badge/swift-3.2-orange.svg?style=flat)](https://developer.apple.com/swift)\n[![Swift 4.0](https://img.shields.io/badge/swift-4.0-red.svg?style=flat)](https://developer.apple.com/swift)\n[![License](https://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat)](https://opensource.org/licenses/MIT)\n[![Twitter](https://img.shields.io/badge/twitter-@nicklockwood-blue.svg)](http://twitter.com/nicklockwood)\n\n# Sprinter\n\n- [Introduction](#introduction)\n\t- [What?](#what)\n\t- [Why?](#why)\n\t- [How?](#how)\n- [Usage](#usage)\n    - [Installation](#installation)\n    - [Integration](#integration)\n    - [Localization](#localization)\n    - [Thread Safety](#thread-safety)\n    - [Advanced Usage](#advanced-usage)\n\n\n# Introduction\n\n## What?\n\nSprinter is a library for Mac and iOS for formatting strings at runtime using the printf / NSLog format token conventions.\n\nThe 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.\n\nThe name \"Sprinter\" is derived from \"String-Printer\", just like the `sprintf` function in the C standard library.\n\n\n## Why?\n\nAlthough 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:\n\n    \"Hello %s, how are you?\"\n    \nBecause 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.\n\nSwift 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.\n\nSprinter solves these issues by exposing the argument types for each format string, so you can write runtime validation logic and handle errors gracefully.\n\nThe 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.\n\n\n## How?\n\nSprinter implements a robust string format parser based on the original [IEEE printf spec](http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html) along with [Apple's additions](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html) 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.\n\nSprinter includes a comprehensive test suite to ensure spec compliance, and output compatibility with Apple's formatter.\n\n\n# Usage\n\n## Installation\n\nThe 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.\n\nTo install Sprinter using CocoaPods, add the following to your Podfile:\n\n\tpod 'Sprinter', '~\u003e 0.2.0'\n\nSprinter works with Swift 3.2 and 4.x and supports iOS 9 or macOS 10.0 and above\n\n\n## Integration\n\nTo format a string using Sprinter, you first create a `FormatString` instance, as follows:\n\n```swift\nlet formatString = try FormatString(\"I have %i apples and %i bananas\")\n```\n\nNote 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.\n\nYou would use the `print()` method as follows:\n\n```swift\nlet string = try formatString.print(5, 6)\nprint(string) // I have 5 apples and 6 bananas\n```\n\nYou'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:\n\n```swift\nlet formatString = try FormatString(\"I have %y apples\") // throws FormatString.error.unexpectedToken(\"y\")\n\nlet string = try FormatString(\"I have %i apples\").print(\"foo\") // throws FormatString.error.argumentMismatch(1, String.self, Int.self)\n```\n\nYou 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:\n\n```swift\nlet types = formatString.types\nprint(types) // Int, Int\n```\n\nThis 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.\n\n\n## Localization\n\nThe `FormatString` constructor also takes an optional `locale` argument, which can be used to localize the output:\n\n```swift\nlet french = try FormatString(\"I have %i apples\", locale: Locale(identifier: \"fr-FR\"))\n```\n\nThis will affect how locale-specific formatting and punctuation is displayed, for example:\n\n```swift\nlet english = try FormatString(\"%'g\", locale: Locale(identifier: \"en-US\"))\ntry print(english.print(1234.56)) // 1,234.56\n\nlet french = try FormatString(\"%'g\", locale: Locale(identifier: \"fr-FR\"))\ntry print(french.print(1234.56)) // 1 234,56\n\nlet german = try FormatString(\"%'g\", locale: Locale(identifier: \"de-DE\"))\ntry print(german.print(1234.56)) // 1.234,56\n```\n\n## Thread Safety\n\nIt is safe to create `FormatString` instances on a background thread.\n\nOnce created, a given `FormatString` instance is stateless, so the same instance can safely be used to print strings on multiple threads concurrently.\n\n\n## Advanced Usage\n\nIt may seem cumbersome to have to create a `StringFormat` object before printing, but it serves two purposes:\n\n1. 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.\n\n2. The expensive string parsing and `NumberFormatter` initialization steps can be performed once and then stored, not repeated each time the string is displayed.\n\nFor 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.\n\nA 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:\n\n\n```swift\nprivate var cache = [String: FormatString]()\nprivate let queue = DispatchQueue(label: \"com.Sprinter\")\n\nfunc localizedString(_ key: String, _ args: Any...) -\u003e String {\n    do {\n        var formatString: FormatString?\n        queue.sync { formatString = cache[key] }\n        if formatString == nil {\n            formatString = try FormatString(NSLocalizedString(key, comment: \"\"), locale: Locale.current)\n            queue.async { cache[key] = formatString }\n        }\n        return try formatString?.print(arguments: args) ?? \"\"\n    } catch {\n        // Crash in development, but not in production\n        assertionFailure(\"\\(error)\")\n        return \"\"\n    }\n}\n```\n\nThis function provides:\n\n* A convenient API for displaying keys from your `Localizable.strings` file\n* Encapsulated error handling, which will crash in development but fail gracefully in production\n* Thread-safe caching of `FormatString` instances for better performance\n\nThis is just an example approach, but it should work for most use cases.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicklockwood%2FSprinter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnicklockwood%2FSprinter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicklockwood%2FSprinter/lists"}