Breaking Down String Format Specifiers in Swift
Before we start
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.2, and Swift 5.3
You will be expected to be able to run and use Swift’s Playgrounds
Keywords and Terminology:
String Format Specifiers: This article summarises the format specifiers supported by string formatting methods and functions.
Apple already have a Strings Programming guide for String Format Specifiers, but how are these actually used? In steps this guide
$d and %D represent a signed 32-bit Integer, that is an Int.
In the most basic case we can use the initializer for String to format the Integer
Interpolate with %d
let basicNumber: Int = 42
print(String(format: "%d", basicNumber)) // 42
print(String(format: "Basic Number: %d", basicNumber)) // Basic Number: 42
But we can do more with this initializer.
*Numbers before the decimal point**
let leadingZeros: Int = 5
let leadingStr1 = String(format: "%03d", leadingZeros) // 005
let leadingStr2 = String(format: "%05d", leadingZeros) // 00005
*Numbers after the decimal point**
let trailingZeros: Float = 7.9857
let trailingStr1 = String(format: "%.2f", trailingZeros) // 7.99
let trailingStr2 = String(format: "%.4f", trailingZeros) // 7.9857
**Convert from Integer to hex**
In C, %2X defines the field width — if the hex representation of the value consists of less than 2 digits a prefix will be appended and we are guaranteed to have a field width of 2.
let hexNumber: Int = 1616
let hexStr1 = String(format: "%2X", hexNumber) // 650
%f represents a 64-bit floating-point number, that is a double and it is printed in decimal notation.