DocsLanguage Guide
Strings and Characters
String literals, interpolation and format specs, Unicode, indices and substrings.
A string is a run of text, such as "hello, world" or "Straße". Sable's String is a value type: when you assign one to another variable or pass it to a function, the receiver gets its own string, and changing one never changes the other. Under the hood the bytes are shared until one side writes, so copying a string costs a reference count, not a copy of its text.
Text in Sable is Unicode throughout. A String stores its text as UTF-8, a Char is one Unicode scalar value, and the library gives you views of a string's bytes, scalars and user-perceived characters when you need to work at one of those levels. This chapter covers how you write strings, how you build them from other values with interpolation and format specs, and how you walk through, cut and compare them.
String Literals#
A string literal is text between double quotes. Use one to give a constant or variable its first value:
let greeting = "Hello, Sable"Sable infers String for greeting, because that is the type of a string literal. A literal is written on one line; a line break before the closing quote is an error.
Multi-line String Literals#
When the text spans several lines, open and close it with three double quotes:
let usage = """ Usage: inventory [options] <file> Options: --verbose Print every item as it is read """print(usage)Usage: inventory [options] <file>Options: --verbose Print every item as it is readThree rules shape a multi-line literal:
- The text begins on the line after the opening
""". Nothing but the end of the line may follow those quotes (S0023). - The closing
"""sits on a line of its own, and its indentation is stripped from every line. That lets you indent the literal to match the surrounding code without the indentation becoming part of the string. Lines indented further than the closing quotes keep the extra spaces, as--verbosedoes above. A line that is not blank but is indented less than the closing quotes would lose some of its text, so it is an error (S0024). - The line break just before the closing
"""is not part of the string. To end the string with a line break, leave a blank line before the closing quotes.
A long line can be broken in the source without breaking it in the string: a backslash at the very end of a line joins it to the next one.
let notice = """ The warehouse closes at six; orders placed after \ that are shipped the next morning. """// one line: "The warehouse closes at six; orders placed after that are shipped the next morning."The joined line still loses the closing delimiter's indentation, like every other line.
Raw String Literals#
Inside an ordinary literal a backslash starts an escape. Sometimes you want the backslashes kept, as in a regular expression or a Windows path. A raw string is written between #" and "#, and everything inside is taken exactly as written: no escapes, no interpolation, and a plain " needs no backslash.
let pattern = #"\d+\.\d+"# // the characters \ d + \ . \ d +let quoted = #"She said "hello" and left"#let template = #"Total: \(amount)"# // the characters \ ( a m o u n t ), not a holeIf the text itself contains "#, add more hashes on both sides. The literal ends only at a quote followed by the same number of hashes it opened with:
let snippet = ##"print(#"raw"#)"##A raw literal can span lines as well, opened with #""" and closed with """#; its text is taken as it lies between them.
Special Characters in String Literals#
An ordinary or multi-line string literal can contain these escapes:
| Escape | Meaning |
|---|---|
\0 |
the null character |
\\ |
a backslash |
\t |
a horizontal tab |
\n |
a line feed |
\r |
a carriage return |
\" |
a double quote |
\' |
a single quote |
\u{n} |
the Unicode scalar whose code point is n, in hex |
\(expr) |
an interpolation (see below) |
let motto = "\"Measure twice,\" she said.\n\tCut once."let heart = "\u{2665}" // ♥let face = "\u{1F600}" // 😀Characters#
A Char is one Unicode scalar value: a code point in the range U+0000 to U+10FFFF, excluding the surrogates. It is not a UTF-16 code unit, as C#'s char is, and not a grapheme cluster, as Swift's Character is. Character literals use single quotes, and accept the same escapes as strings:
let initial: Char = 'S'let tab = '\t'let apostrophe = '\''let grin = '\u{1F600}' // one Char, however many bytes it takes in UTF-8Iterating over a string gives you its Chars:
for c in "Sable" { print(c)}SableA Char knows a good deal about itself. A few of its members:
let c = 'é'print(c.isLetter) // trueprint(c.isUppercase) // falseprint(c.uppercased()) // É (a String: some scalars uppercase to several)print(c.codePoint) // 233print(c.utf8Length) // 2print('7'.digitValue()) // 7, an Int?There are also isDigit, isWhitespace, isPunctuation, isAlphanumeric, the ASCII-only tests (isAscii, isAsciiLetter, isAsciiDigit, …), generalCategory, and Char.fromCodePoint(value:), which gives a Char? because not every integer is a scalar.
Building Strings#
+ joins two strings into a new one, and += appends to a variable:
var label = "Order"label += " #"label = label + "1042"print(label) // Order #1042A string that is empty has isEmpty set:
var note = ""if note.isEmpty { note = "(none)"}To build a string from a sequence of characters, pass the sequence to String's initialiser:
let letters: Char[] = ['a', 'b', 'c']let word = String(letters) // "abc"For long-running assembly of text, print(_:to:) writes a line into any TextWriter, a String among them:
var report = ""print("first line", to: &report)print("second line", to: &report)// report == "first line\nsecond line\n"String Interpolation#
Interpolation builds a string from a mix of literal text and values. Inside a string literal, \(expression) is a hole: the expression is worked out, and its value is written into the string at that point.
let item = "lamp"let quantity = 3let price = 24.5print("\(quantity) × \(item) at \(price) each: \(F64(quantity) * price)")3 × lamp at 24.5 each: 73.5The expression in a hole is an ordinary expression, so it can call functions, use operators, and even contain another string literal with holes of its own. A hole must close on the line it opens on (S0021). Interpolation works in multi-line literals too, but not in raw ones.
What a hole writes depends on the value's type:
| Value | Written as |
|---|---|
a String |
the text itself |
a number, Bool, Char |
its text: 42, 3.5, true, x |
a Formattable value |
whatever its format method writes |
| an enum | its case's name: "\(GeneralCategory.MathSymbol)" is MathSymbol |
a Debug value |
as it describes itself, so an array is [1, 2] and a @derive(Debug) struct is Order(id: 7, …) |
| anything else | as Reflect.describe describes it |
The order in that table is the order Sable looks: a type that is Formattable writes itself that way; otherwise one that is Debug describes itself; otherwise reflection gives a description. There is no CustomStringConvertible-style protocol to implement for printing: make a type Formattable (below) or Debug (covered in Derivation and Source Generators).
A float with no format spec is written in the shortest digits that read back as the same value:
print("\(0.1 + 0.2)") // 0.30000000000000004print("\(2.0)") // 2.0Format Specs#
A colon after a hole's expression starts a format spec, which says how to write the value: how wide, which way to align it, how many decimals, which radix. The spec runs to the hole's closing parenthesis.
let total = 1234567let ratio = 0.125let n = 255print("[\(n:#06x)]") // [0x00ff]print("[\(19.5:>10.2)]") // [ 19.50]print("[\(total:,)]") // [1,234,567]print("[\(ratio:.1%)]") // [12.5%]print("[\("sable":*^9)]") // [**sable**]print("[\("tab\there":?)]") // ["tab\there"]A spec is text, not code, in this order, every part optional:
[[fill] align] [sign] [#] [0] [width] [, or _] [.precision] [kind]| Part | Meaning |
|---|---|
align |
< left, ^ centre, > right. Without one, a number goes right and text left. |
fill |
any one scalar written before an alignment, used to pad (a space when none is given) |
sign |
+ signs every number, - only negative ones (the default), a space puts a space where + would be |
# |
writes an integer's radix prefix (0x, 0o, 0b); for g, keeps the trailing zeros it would drop |
0 |
pads a number with zeros after its sign, out to the width |
width |
the least number of scalars written |
, or _ |
a separator between each three digits of a number's whole part (for _ in a radix other than ten, each four) |
.precision |
digits after a float's point (for g, digits in all); for a string, how many scalars are kept |
kind |
d x X o b for integers; e E f g G % for floats; ? for anything, written as Debug describes it |
Some examples of each part at work:
print("\(255:x) \(255:X) \(8:o) \(5:b)") // ff FF 10 101print("\(255:#x) \(5:#b)") // 0xff 0b101print("\(5:+) \(-5:+) \(5: )") // +5 -5 5print("[\(42:5)] [\(42:<5)] [\(42:^6)]") // [ 42] [42 ] [ 42 ]print("\(-42:06) \(1234:08,)") // -00042 0,001,234print("\(1234567:_)") // 1_234_567print("\(2.0:.3f) \(1234.5:.2e)") // 2.000 1.23e+03print("\(123456789.0:.3g) \(2.5:#.4g)") // 1.23e+08 2.500print("\(0.25:%)") // 25%print("[\("sable":.3)] [\("ab":5)]") // [sab] [ab ]print("\('c':?) \("q":?)") // 'c' "q"With a precision, a float's exact value is rounded to the nearest digit, ties going to even; without one it is written in its shortest round-tripping digits, as with no spec at all. The ? kind combines with # for a description laid out over several lines, "\(order:#?)", which is handy for nested values.
The fill can be any scalar except a quote, a backslash or a parenthesis, since those would end or nest the hole. A ternary inside a hole keeps its own colon; only a colon after the whole expression starts the spec, so "\(ok ? a : b:x)" writes a or b in hex.
Checked at Compile Time#
Because the spec is part of the literal, the compiler reads it and checks it against the value's type:
- text that is not a spec at all is S3660;
- a kind the type cannot be written in, such as
"\(name:x)"on aString, is S3661; - an option the type would ignore, such as a precision on an integer or a sign on a string, is S3662;
- for a type that is not
Formattable, anything but a fill, an alignment, a width or?is S3663. Such a value is padded as it would otherwise be written.
So "\(count:.2)" with an Int count does not compile, rather than quietly writing the number without decimals.
Formattable and FormatSpec#
A spec becomes a FormatSpec value, a struct in Sable.Core with a field for each part (fill, alignment, sign, alternate, zeroPadded, width, separator, precision, kind). It is handed to the value's format method, the one requirement of the Formattable protocol:
protocol Formattable { fn format(_ spec: FormatSpec) -> String}So a type of your own can honour specs. Here a temperature uses the precision for its digits and the width and alignment for padding, with padded, which pads text as the spec says:
struct Temperature: Formattable { var celsius: F64 fn format(_ spec: FormatSpec) -> String { var digits = FormatSpec() digits.precision = spec.precision ?? 1 return spec.padded(celsius.format(digits) + "°C") }}let today = Temperature(celsius: 21.456)print("[\(today)]") // [21.5°C]print("[\(today:>10.2)]") // [ 21.46°C]You can also read a spec at run time with FormatSpec.parse("*^8"), which throws a ParseError if the text is not one.
Strings Are UTF-8#
A String holds its text as UTF-8 bytes. That has consequences you should know about:
countis the number of Unicode scalars, worked out by walking the bytes.utf8Countis the number of bytes, which the string knows at once.- A string cannot be indexed by an integer: the tenth scalar might start at byte 10 or byte 40. Positions in a string are
String.Indexvalues instead. isAsciitells you every scalar is one byte, so the counts agree.
let city = "Zürich"print(city.count) // 6print(city.utf8Count) // 7: 'ü' takes two bytesprint(city.isAscii) // falseString Indices#
A String.Index is a byte offset into the string, always at the start of a scalar. A string has a startIndex, the position of its first scalar, and an endIndex, the position just past its last one. You step from one index to another with index(after:), index(before:) and index(_:offsetBy:), and read the Char at an index with a subscript:
let word = "Grüße"print(word[word.startIndex]) // Glet third = word.index(word.startIndex, offsetBy: 2)print(word[third]) // üprint(word[word.index(before: word.endIndex)]) // eendIndex is not a valid position to read; reading there, or stepping past either end, traps. For the common cases there are shortcuts: first and last (each a Char?), index(atScalar:), which walks to the nth scalar, and distance(from:to:), which counts the scalars between two indices.
Searching gives you indices too. firstIndex(of:) and lastIndex(of:) take a Char, a String or anything else that is a Pattern, and firstRange(of:) gives the range a match covers:
let path = "reports/2026/summary.txt"if let slash = path.lastIndex(of: '/') { print(path[path.index(after: slash)...]) // summary.txt}Counting From the End#
As with arrays, a string can be read at a position counted back from its end with ^n: ^1 is the last character, ^2 the one before it. For a string, Sable finds that position by stepping back from the end a scalar at a time.
let code = "INV-20931"print(code[^1]) // 1print(code[^5...]) // 20931print(code[..<^6]) // INV^0 is the end itself, so reading code[^0] is an error. A string only reads through these: code[^1] = 'x' is refused (S3010), because a String is not a mutable collection of Chars. The operator itself is covered with arrays in Arrays and Collections.
Views of a String#
When you need a level other than scalars, a string offers views of itself. None of them copies the text.
| View | Elements | Kind of collection |
|---|---|---|
text.utf8 |
the UTF-8 bytes, U8 |
random access, by Int offset |
text.utf16 |
UTF-16 code units, U16 |
a sequence, for talking to UTF-16 APIs |
text.scalars |
the scalars, Char |
bidirectional, by String.Index |
text.graphemes |
grapheme clusters, Substring |
a sequence (Sable.Text) |
The string itself iterates as its scalars, so text.scalars is mostly useful where you want to name that choice explicitly.
let flag = "🇨🇿"for byte in "hé".utf8 { print(byte) // prints 104, then 195 and 169: 'é' is two bytes}print(flag.count) // 2: two regional-indicator scalarsWhat a reader sees as one character may be several scalars: a flag is two, and é may be written as e followed by a combining accent, U+0301. Those extended grapheme clusters are the Sable.Text module's view:
import Sable.Textlet text = "e\u{301}🇨🇿!"print(text.count) // 5 scalarsprint(text.graphemeCount) // 3 characters, as a reader counts themfor cluster in text.graphemes { print(cluster) // é, then 🇨🇿, then !}Note
Swift makes the grapheme cluster its basic Character and counts strings in them. Sable makes the scalar basic, because scalar operations are cheap and well defined, and leaves graphemes to the views that need Unicode's segmentation tables. Sable.Text also has word and sentence views built the same way.
Substrings#
A range of a string's indices, text[a..<b], or a range counted from the end, text[^4...], gives a Substring. A substring is the original string, held by one reference count, plus the byte offsets where the piece starts and ends: nothing is copied. Its indices are the string's own, so an index found in a piece reads the same scalar in the whole.
let line = "sku=LAMP-01; qty=3"let end = line.firstIndex(of: ';')!let field = line[..<end] // a Substring: "sku=LAMP-01"print(field.count) // 11let kept = field.toString() // a String of its own, copied outBecause a substring keeps its whole string alive, call toString() when you mean to keep a small piece of a large text for long. (A piece that is the whole of its string gives back that string, without a copy.) Stepping or slicing past a piece's ends traps, even though the string goes on beyond them.
The name is Swift's. Sable could not use slice syntax for it: String[:] already means a slice of an array of strings, and a string is not an array of its scalars.
StringProtocol#
What String and Substring share is the StringProtocol protocol: a bidirectional collection of Char at String.Index positions that is Comparable and Hashable. Searching, splitting, trimming, prefixes and parsing are written once over it, so they work on either. The operations that cut text give back the text's own kind:
- a
String'ssplitgivesStrings, each copied out; - a
Substring'ssplitgivesSubstrings of the same string, none copied.
A substring equals, orders as and hashes as the string of its scalars, whichever string it came from. So you can look a substring up in a [String: V] dictionary without making a String, and number parsing reads a piece where it lies:
let prices: [String: F64] = ["LAMP-01": 24.5, "DESK-02": 199.0]let record = "LAMP-01,3"if let parts = record.splitOnce(",") { let (sku, qty) = parts // two Substrings of 'record' let count = qty.toInt() ?? 0 // parsed in place, no String made print(prices[sku] ?? 0.0) // looked up by the Substring: 24.5}Writing your own text functions over some StringProtocol, or a generic S: StringProtocol, lets them take either kind, as described in Generics.
Comparing Strings#
Two strings are equal with == when they hold the same Unicode scalars in the same order. < and the other comparisons order strings scalar by scalar, the first difference deciding and a prefix coming first. Since UTF-8's byte order matches the scalars' order, that is a fast byte comparison.
print("apple" == "apple") // trueprint("apple" < "banana") // trueprint("Zebra" < "apple") // true: 'Z' (U+005A) comes before 'a' (U+0061)Equality is by scalars, not by appearance: "é" written as one scalar (U+00E9) and as e plus U+0301 are different strings. To compare text as a reader would, normalise both first with Sable.Text's normalized(.NFC).
For other orders, compare(_:options:) takes String.CompareOptions, a flag set: .IgnoringCase folds case, and .Numeric compares runs of digits as numbers, so "file9" comes before "file10". equals(_:ignoringCase:) is the shortcut for equality.
let order = "file9".compare("file10", options: .Numeric) // .Lessprint("Sable".equals("SABLE", ignoringCase: true)) // truePrefixes and suffixes are checked with hasPrefix and hasSuffix, each taking a pattern:
let file = "summary.txt"if file.hasSuffix(".txt") { print("a text file")}Common String Operations#
The standard library's string API is broad; these are the members you will reach for most. Each one that takes a pattern accepts a Char, a String or a Substring, and most also have a form that takes a (Char) -> Bool test, such as contains(where:).
| Member | What it does |
|---|---|
contains(p), count(of: p) |
whether, and how often, the pattern occurs |
firstIndex(of:), firstRange(of:), ranges(of:) |
where it occurs |
replacing(p, with: s) |
a copy with each occurrence replaced |
split(p), splitWhitespace(), lines() |
the pieces between separators, spaces or line breaks |
splitOnce(p), splitLastOnce(p) |
the two sides of the first or last occurrence, or none |
trimmed(), trimmedStart(), trimmedEnd() |
without the whitespace at either or both ends |
trimmingPrefix(p), trimmingSuffix(p) |
without the pattern at that end |
uppercased(), lowercased(), caseFolded() |
case mapped by Unicode's full rules ("ß" uppercases to "SS") |
paddedStart(toWidth:), paddedEnd(toWidth:) |
padded with spaces, or another fill |
repeated(n), reversed() |
the text n times over, or its scalars in reverse |
isBlank |
whether it is empty or only whitespace |
toInt(), toF64(), … |
the number it writes, or none |
Int.parse(s), F64.parse(s), … |
the same, throwing a ParseError that says what was wrong |
And on an array of strings, joined(separator:) puts them back together:
let csv = " lamp, desk ,chair "let names = csv.split(",").map { $0.trimmed() }print(names.joined(separator: " | ")) // lamp | desk | chairprint("Straße".uppercased()) // STRASSEprint("42".toInt() ?? 0) // 42Closures like { $0.trimmed() } are covered in Closures. Sable.Text adds more again: regular expressions, Base64 and hex, encodings other than UTF-8, normalisation, and word and sentence segmentation.