Pure Programmer
Blue Matrix


Cluster Map

Output Formatting

We have seen the basic ability to convert values to strings and output them to the console ([[stdout]]). Sometimes, however, we would like more control on the formatting used to output values. Fortunately we have formatted output functions that help us with that goal.

C-Style printf()

In the olden days when the C language was developed in the 1970's it contained a novel new way of formatting output called the printf() function. This function allows one to specify a format string followed by values that will be substituted into the format string based on the type specifiers found in the format string. This approach has proven very popular and has been copied in many languages since.

With formatted output we must provide a format string that can contain literal text interspersed with type specifiers. The type specifiers are placeholders that identify where and how a value is to be formatted and inserted into the string on output. Type specifiers start with a percent sign (%), followed by an optional flag, followed by field width and/or precision, followed by one or two characters identifying the type of the value (called the type specifier). Only the percent sign and the type specifier is required, the other components are optional.

%[flag][width][.precision][type specifier]

In addition to the format string, we also provide the values to be formatted to the function. We can have multiple type specifiers in the format string as long as we provide the matching number of additional arguments. The first argument is formatted by the first type specifier, the second argument by the second type specifier, and so on. Swift has printf() style formatting functionality built-in to the String constructor. We can combine this with the Swift print() function to achieve a Swift version of printf().

printf() Illustration
printf() specifiers must match arguments in order

Any other characters in the format string that are not part of a type specifier are printed verbatim. For example:

print(String(format: "Page count is %d", numPages));
print(String(format: "PI: %.2f", pi));
print(String(format: "Title and Page Count: %s %d", title, numPages));
print(String(format: "%d of %d", currentPage, numPages));

Some of the type specifiers available are listed in the table below.

Frequently Used Type Specifiers
SpecifierValue TypeDescription
dsigned IntSigned decimal
uunsigned IntUnsigned decimal
xunsigned IntHexadecimal (lowercase)
Xunsigned IntHexadecimal (uppercase)
ldsigned Int64Signed decimal
luunsigned Int64Unsigned decimal
lxunsigned Int64Hexadecimal (lowercase)
lXunsigned Int64Hexadecimal (uppercase)
fDoubleDecimal floating point
eDoubleScientific notation (lowercase)
EDoubleScientific notation (uppercase)
gDoubleShortest representation: %e or %f
GDoubleShortest representation: %E or %F
@StringUnicode String
pvoid*Pointer address in hexadecimal
%noneOutputs literal %

The type specifiers d,u,x or X can be modified to print a short int (16-bit) by prefacing the print specifier with an 'h' as in 'hd' or 'hx'. They may also be modified to print a long int (64-bit) by prefacing the specifier with an 'l' as in 'ld' or 'lx'.

Print Flags
FlagDescription
-Left-justify within the given field width; Right justification is the default.
+Result is preceeded with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
#Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively. Used with e, E, f, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0Left-pads the number with zeroes (0) instead of spaces

The field width and precision are simply integer values separated by a period (.). One may use either in the type specifier, both or none. Field width sets the number of characters that will be used to output the value padded with spaces if necessary to achieve the field width. The precision specifier is only useful for formatting floating point and string values. For floating point values it limits the number of decimal places after the decimal point. For strings it truncates the string to the specified number of characters.

OutputFormatting1.swift
#!/usr/bin/env swift;
import Foundation
import Utils

// Begin Main
let a:Int = 326
let b:Int = -1
let c:Int = 2015
let i1:Int64 = 65000
let i2:Int64 = -2
let i3:Int64 = 3261963
let f1:Double = 3.1415926
let f2:Double = 2.99792458e9
let f3:Double = 1.234e-4
let c1:Int = Utils.ord("A")
let c2:Int = Utils.ord("B")
let c3:Int = Utils.ord("C")
let s1:String = "Apples"
let s2:String = "and"
let s3:String = "Bananas"
let b1:Bool = true
let b2:Bool = false

print(String(format:"Decimals: %d %d %d", a, b, c))
print(String(format:"Hexadecimals: %#x %#x %#x", a, b, c))
print(String(format:"Long Decimals: %d %d %d", i1, i2, i3))
print(String(format:"Long Hexadecimals: %016x %016x %016x", i1, i2, i3))

print(String(format:"Fixed FP: %f %f %f", f1, f2, f3))
print(String(format:"Exponential FP: %e %e %e", f1, f2, f3))
print(String(format:"General FP: %g %g %g", f1, f2, f3))
print(String(format:"General FP with precision: %.2g %.2g %.2g", f1, f2, f3))

print(String(format:"Boolean: %@ %@", String(b1), String(b2)))
print(String(format:"Character: %@ %@ %@", Utils.chr(c1), Utils.chr(c2), Utils.chr(c3)))
print(String(format:"String: %@ %@ %@", s1, s2, s3))

exit(EXIT_SUCCESS)

Output
$ swiftc OutputFormatting1.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

To print booleans and characters we must first convert them to Strings and use the String type specifier %@

C-Style sprintf()

Along with the printf() function, the C language introduced a similar function called sprintf(). Instead of printing a formatted string to the console ([[stdout]]), it formats and then returns a string. This more general form has many uses not only for console output but for [[GUI]] output and file output.

The Swift version of sprintf() is found in the String constructor with the special named argument format:.

OutputFormatting2.swift
#!/usr/bin/env swift;
import Foundation
import Utils

// Begin Main
let a:Int = 326
let b:Int = -1
let c:Int = 2015
let i1:Int64 = 65000
let i2:Int64 = -2
let i3:Int64 = 3261963
let f1:Double = 3.1415926
let f2:Double = 2.99792458e9
let f3:Double = 1.234e-4
let c1:Int = Utils.ord("A")
let c2:Int = Utils.ord("B")
let c3:Int = Utils.ord("C")
let s1:String = "Apples"
let s2:String = "and"
let s3:String = "Bananas"
let b1:Bool = true
let b2:Bool = false

var s:String

s = String(format:"Decimals: %d %d %d", a, b, c)
print(s)
s = String(format:"Hexadecimals: %#x %#x %#x", a, b, c)
print(s)
s = String(format:"Long Decimals: %d %d %d", i1, i2, i3)
print(s)
s = String(format:"Long Hexadecimals: %016x %016x %016x", i1, i2, i3)
print(s)

s = String(format:"Fixed FP: %f %f %f", f1, f2, f3)
print(s)
s = String(format:"Exponential FP: %e %e %e", f1, f2, f3)
print(s)
s = String(format:"General FP: %g %g %g", f1, f2, f3)
print(s)
s = String(format:"General FP with precision: %.2g %.2g %.2g", f1, f2, f3)
print(s)

s = String(format:"Boolean: %@ %@", String(b1), String(b2))
print(s)
s = String(format:"Character: %@ %@ %@", Utils.chr(c1), Utils.chr(c2), Utils.chr(c3))
print(s)
s = String(format:"String: %@ %@ %@", s1, s2, s3)
print(s)

exit(EXIT_SUCCESS)

Output
$ swiftc OutputFormatting2.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

String Interpolation

Many languages have the ability to replace variables written directly into strings. This variable substitution in strings is know as variable interpolation. Swift supports variable interpolation by simply wrapping the variable name in a pair of parentheses, prefixed by a backslash (\)> such as \(variable_name). This interpolation mechanism also supports simple expressions in addition to a single variable name.

OutputFormatting3.swift
#!/usr/bin/env swift;
import Foundation

// Begin Main
let FICA_RATE:Double = 0.0765
let PAY_RATE:Double = 20.0
var annual_salary:Double

annual_salary = PAY_RATE * 2080.0
print("FICA Tax Rate: \(FICA_RATE)")
print("Annual Salary: \(annual_salary)")
print("FICA Tax: \(FICA_RATE * annual_salary)")

exit(EXIT_SUCCESS)

Output
$ swiftc OutputFormatting3.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation) $ swiftc OutputFormatting3.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation) $ swiftc OutputFormatting3.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation) $ swiftc OutputFormatting3.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation) $ swiftc OutputFormatting3.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

Modern Message Formatting

The methods for formatting strings and output discuss so far have some limitations when it comes to localizing software. The positional approaches taken by the printf() style functions poses difficulties to localization because often during translation the order of words and thus the substition specifiers must change but the hard-code argument list in our code can not change to match. Variable interpolation has its drawbacks because you are actually putting code into the strings. When externalizing the strings (removing them from the code and putting them in a separate file) necessary for localization, it is not desirable to export variables and expressions from our code to the localization file where they can be changed.

This is why message formatting approaches have been developed that use substitution specifiers that specify which argument to the message format function is to be used. This allows the substitution specifiers to be in a different order (and perhaps re-ordered during localization) than the formal arguments to the message format function. These substitution specifiers are also not executable code as is the case with variable interpolation so it is much safer to externalize from our program code as we will see in the section on Internationalization.

A format() function that is modelled after the Python format() function is provided in the [[Pure Programmer Swift Utils Class]]. Save the "Utils.swift" source in the same folder where your source files reside. Once this is done, you may use the import for "Utils" to be able to use the Utils module in your programs.

#!/usr/bin/env swift

import Foundation
import Utils

var first = "First";
var middle = "Middle";
var last = "Last";

var s = Utils.format("{2}, {0} {1}", first, middle, last);
print(s);
Pure Programmer Utils Example

The format() method uses a pair of curly brackets to identify substition placeholders in the format string. Each pair of curly brackets contains a number from 0 to the number of addtional arguments - 1. This number refers to the position in the argument list of the value that will be used in the substitution. This allows values in the argument list to be used in any order needed in the format string or even used more than once.

format() Illustration
format() specifiers can match any argument

Following the position number in the substitution placeholder is an optional type specifier. The type specifier is separated from the position number by a colon. If you don't wish to use a type specifier then the type is assumed to be string. Some of the type specifiers available are listed in the table below.

Frequently Used Type Specifiers
SpecifierValue TypeDescription
bintegerbinary
dintegerdecimal
ointegeroctal
xintegerhexadecimal (lowercase)
Xintegerhexadecimal (uppercase)
fdoublefixed notation
edoublescientific notation (lowercase)
Edoublescientific notation (uppercase)
gdoubleshortest representation: e or f
Gdoubleshortest representation: E or f
cintegersingle character
sstringstring of characters

Like we have seen in printf(), the format() specifiers can take optional modifiers that change how the value is to be formatted. The full definition of the specifiers, including optional components is as follows:

{[arg-pos]:[fill-and-align][sign][#][0][width][.precision][type specifier]}

The fill-and-align option is an optional fill character (which can be any character other than { or }), followed by one of the align options <, >, ^. If no fill character is specified, then the space character is used.

Align Options
OptionDescription
<Left-justify within the given field width. This is the default for non-numeric types.
>Right-justify within the given field width. This is the default for numeric types.
^Aligns the value in the center of the field.

The sign option is one of +, - or the space character.

Sign Options
OptionDescription
+Signifies that a sign character should be output for all values (+ for positive and - for negative).
-Signifies that a sign character should be output for negative values only. This is the default for numeric types.
<space>Signifies that a leading space should be used for positive values and a - should be output for negative values.

The # option causes alternate formatting to be used.

The 0 option pads the field with leading zeros (following any indication of sign or base) to the field width. If the 0 option and an align option both are used, the 0 option is ignored.

The width option is a positive decimal number. If present, it specifies the minimum field width. If the formatted value can not fit within the field width the entire value will be inserted causing the field to be larger than width.

The precision option is a . followed by a non-negative decimal number. This option indicates the precision to use when formatting a value. For floating-point types, precision specifies the formatting precision, i.e. the number of places after the decimal point to display. For string types, it specifies how many characters from the string will be used.

OutputFormatting4.swift
#!/usr/bin/env swift;
import Foundation
import Utils

// Begin Main
let first:String = "First"
let middle:String = "Middle"
let lastname:String = "Last"
let left:String = "Left"
let center:String = "Center"
let right:String = "Right"
let favorite:String = "kerfuffle"
let i1:Int64 = 3261963
let i2:Int16 = -42
let fp1:Double = 3.1415926
let fp2:Double = 2.99792458e9
let fp3:Double = -1.234e-4

var s:String = Utils.format("{2}, {0} {1}", first, middle, lastname)
print(s)
s = Utils.format("{0} {1} {2}", left, center, right)
print(s)
s = Utils.format("Favorite number is {0}", i1)
print(s)
s = Utils.format("Favorite FP is {0}", fp1)
print(s)

var c:Int = Utils.codepoint_at(favorite, 0)
print(Utils.format("Favorite c is {0:c}", c))
print(Utils.format("Favorite 11c is   |{0:11c}|", c))
print(Utils.format("Favorite <11c is  |{0:<11c}|", c))
print(Utils.format("Favorite ^11c is  |{0:^11c}|", c))
print(Utils.format("Favorite >11c is  |{0:>11c}|", c))
print(Utils.format("Favorite .<11c is |{0:.<11c}|", c))
print(Utils.format("Favorite _^11c is |{0:_^11c}|", c))
print(Utils.format("Favorite  >11c is |{0: >11c}|", c))

c = 0x1F92F
print(Utils.format("Favorite emoji c is {0:c}", c))

print(Utils.format("Favorite s is {0:s}", favorite))
print(Utils.format("Favorite .2s is {0:.2s}", favorite))
print(Utils.format("Favorite 11s is     |{0:11s}|", favorite))
print(Utils.format("Favorite 11.2s is   |{0:11.2s}|", favorite))
print(Utils.format("Favorite <11.2s is  |{0:<11.2s}|", favorite))
print(Utils.format("Favorite ^11.2s is  |{0:^11.2s}|", favorite))
print(Utils.format("Favorite >11.2s is  |{0:>11.2s}|", favorite))
print(Utils.format("Favorite .<11.2s is |{0:.<11.2s}|", favorite))
print(Utils.format("Favorite *^11.2s is |{0:*^11.2s}|", favorite))
print(Utils.format("Favorite ->11.2s is |{0:->11.2s}|", favorite))

print(Utils.format("Favorite d is {0:d}", i1))
print(Utils.format("Another d is {0:d}", i2))
print(Utils.format("Favorite b is {0:b}", i1))
print(Utils.format("Another B is {0:b}", i2))
print(Utils.format("Favorite o is {0:o}", i1))
print(Utils.format("Another o is {0:o}", i2))
print(Utils.format("Favorite x is {0:x}", i1))
print(Utils.format("Another X is {0:X}", i2))
print(Utils.format("Favorite #b is {0:#b}", i1))
print(Utils.format("Another #B is {0:#b}", i2))
print(Utils.format("Favorite #o is {0:#o}", i1))
print(Utils.format("Another #o is {0:#o}", i2))
print(Utils.format("Favorite #x is {0:#x}", i1))
print(Utils.format("Another #X is {0:#X}", i2))
print(Utils.format("Favorite 11d is   |{0:11d}|", i1))
print(Utils.format("Favorite +11d is  |{0:+11d}|", i1))
print(Utils.format("Favorite 011d is  |{0:011d}|", i1))
print(Utils.format("Favorite 011x is  |{0:011x}|", i1))
print(Utils.format("Favorite #011x is |{0:#011x}|", i1))

print(Utils.format("Favorite f is {0:f}", fp1))
print(Utils.format("Another f is {0:f}", fp2))
print(Utils.format("One more f is {0:f}", fp3))
print(Utils.format("Favorite e is {0:e}", fp1))
print(Utils.format("Another e is {0:e}", fp2))
print(Utils.format("One more e is {0:e}", fp3))
print(Utils.format("Favorite g is {0:g}", fp1))
print(Utils.format("Another g is {0:g}", fp2))
print(Utils.format("One more g is {0:g}", fp3))
print(Utils.format("Favorite .2f is {0:.2f}", fp1))
print(Utils.format("Another .2f is {0:.2f}", fp2))
print(Utils.format("One more .2f is {0:.2f}", fp3))
print(Utils.format("Favorite .2e is {0:.2e}", fp1))
print(Utils.format("Another .2e is {0:.2e}", fp2))
print(Utils.format("One more .2e is {0:.2e}", fp3))
print(Utils.format("Favorite .2g is {0:.2g}", fp1))
print(Utils.format("Another .2g is {0:.2g}", fp2))
print(Utils.format("One more .2g is {0:.2g}", fp3))
print(Utils.format("Favorite 15.2f is |{0:15.2f}|", fp1))
print(Utils.format("Another 15.2e is  |{0:15.2e}|", fp2))
print(Utils.format("One more 15.2g is |{0:15.2g}|", fp3))

exit(EXIT_SUCCESS)

Output
$ swiftc OutputFormatting4.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

Questions

Projects

More ★'s indicate higher difficulty level.

References