Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 146 ยท Getting Started

Strings

Learn how Swift strings work - multiline and raw literals, Unicode and grapheme clusters, why indices are not integers, common methods and Substring, with runnable examples.

Text is everywhere in programs: names, messages, file contents, JSON. Swift's String is one of the most carefully designed string types in any mainstream language, and also one that surprises newcomers, because you cannot write name[3] to get the fourth letter. That is not an oversight. It is a consequence of Swift treating text the way people read it, as a sequence of visible symbols, and not as a row of bytes.

This lesson shows how to create and combine strings, how Swift counts characters (and why that matters for emoji and accents), why indices are a special type, which methods you will use daily, and how Substring keeps slicing cheap. Building text with \(...) and formatting numbers has its own lesson: String Interpolation and Formatting. The type itself was introduced in Basic Types.

Creating and combining strings

A string literal is text in double quotes. String is a value type: assigning it to another variable copies it (cheaply, Swift shares the storage until one side changes), so changing one never affects the other.

Swift Creating, joining and comparing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

+ joins two strings, += and append extend a variable. The copy shows value semantics: after message grew, copy is untouched. Comparison with == and < works on the text itself, in Unicode order, so uppercase letters sort before lowercase ones ("Zebra" < "apple" is true). For human-friendly sorting, such as a name list in a user interface, you would use a locale-aware comparison; see Text Processing.

Multiline and raw literals

Three double quotes start a multiline string literal. The text starts on the line after the opening quotes, and the position of the closing """ decides how much indentation is removed from every line. That lets you indent the literal with your code without that indentation ending up in the text.

Wrapping the literal in # characters makes it a raw string: backslashes and quotes are ordinary characters, and an escape or interpolation needs the same number of # after the backslash. Raw strings are the right tool for regular expressions, Windows paths and snippets of JSON.

Swift Multiline and raw string literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two lines of the poem keep their relative indentation (the second one stays two spaces further in), while the four spaces in front of the closing """ are stripped from all of them. In the raw strings, \n is printed as the two characters backslash and n, and only \#( ) interpolates. A normal string uses the escapes \n, \t, \", \\ and \u{...} for a Unicode scalar.

Characters, scalars and bytes

Here is the idea that explains most of Swift's string design. What a reader sees as "one character" can be built from several code points. The letter รฉ may be one scalar (U+00E9) or the letter e followed by a combining accent (U+0301). A family emoji is several emoji joined by invisible joiner characters. Swift's Character is a grapheme cluster: everything that is displayed as a single symbol, however many scalars it needs.

Swift Characters, scalars and bytes are different counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both spellings of "cafรฉ" are equal and have count == 4, but they differ in scalars (4 against 5) and bytes (5 against 6). The family emoji is one Character made of five scalars and eighteen UTF-8 bytes. So count tells you how many symbols a reader sees. It does not tell you how much storage the string uses, and when you need that (a protocol with a byte limit, a database column) you ask the utf8 view.

count on a String is O(n): Swift has to walk the text to find grapheme boundaries. Do not call it in a loop condition. If you only need to know whether there is any text, use isEmpty, which is O(1).

Why indices are not integers

Because characters have different widths in memory, "the fifth character" cannot be found by arithmetic. Swift therefore gives strings their own index type, String.Index, and you move around with index(_:offsetBy:), startIndex and endIndex.

Swift Working with String.Index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

startIndex is the first position and endIndex is the position after the last character, so text[text.endIndex] is never valid. The one-sided ranges i... and ..<comma are the compact way to say "from here to the end" and "up to here". A search such as firstIndex(of:) returns an optional index, which you unwrap with if let (Optionals).

An index you compute yourself can go out of range, and that is a runtime trap, not a silent mistake:

Swift An index beyond the end traps (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program stops with Fatal error: String index is out of bounds (together with a crash trace), and the process exits with a failure signal. The fix is to use the form with a limit, text.index(text.startIndex, offsetBy: 10, limitedBy: text.endIndex), which returns nil instead of trapping, or to avoid indices entirely by using prefix, dropFirst and friends, shown next.

On Linux the printed form of an index, for example Optional(5[utf8]), exposes an internal detail (which encoding the index was made in). Never print or store indices; use them immediately, against the same unmodified string.

Everyday methods

The standard library covers most needs without indices at all. Methods that need no import come from Swift itself. A few, such as replacingOccurrences(of:with:) and components(separatedBy:), come from Foundation, so the file needs import Foundation.

Swift Common String methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Some points worth knowing:

  • uppercased() and lowercased() return new strings; Swift strings are values, so nothing is changed in place.
  • prefix, suffix, dropFirst and dropLast are safe: they do not trap if the string is shorter than the number you pass.
  • split returns substrings, and by default it drops empty pieces ("a,b,,c" gives three, not four). Pass omittingEmptySubsequences: false to keep them.
  • reversed() returns a lazy view of the characters, so wrap it in String(...) to get a string.
  • contains("Swi") with a string argument works in modern Swift; contains("x") with a single Character also works.

Inserting and removing by index

Because a String is a value, you can also edit a var string in place, as long as you hand the editing methods a String.Index and not an integer. The methods come in pairs: one acts on a single Character, the other on a whole range.

Method What it does
insert(_:at:) puts one Character before the given index
insert(contentsOf:at:) puts a whole string (or any sequence of characters) before the index
remove(at:) removes the character at the index and returns it
removeSubrange(_:) removes every character in a range
replaceSubrange(_:with:) swaps a range for other text, of any length
removeAll(where:) removes every character that matches a test
Swift Insert, remove and replace by index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Three details trip people up:

  • Insertion is "before". insert(_:at:) with endIndex appends, and with startIndex prepends. Passing an index past endIndex traps, exactly like subscripting does.
  • Mutation invalidates indices. After any insert or remove, an index you computed earlier may point at the wrong place or at nothing. Derive a fresh index from the changed string every time. A loop that removes characters should either go from the end to the start or collect the work first.
  • A range of zero width is an insertion, and an empty replacement is a deletion. replaceSubrange(i..<i, with: "x") inserts, and replaceSubrange(range, with: "") is the same as removeSubrange(range).

Counting still happens in characters, not bytes. Removing one family emoji removes the whole grapheme cluster, so "a๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งb" becomes "ab" with count 2. When you do want integer positions, wrap the index arithmetic in a small helper that stays safe at the ends:

Swift A safe insert at an integer offset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is 1,234,567 and then 1,234,567!: the second call asks for an offset beyond the end, limitedBy: returns nil, and the helper falls back to endIndex. Like all offset arithmetic, index(_:offsetBy:) walks the string character by character, so inserting by offset inside a long loop is slow; prefer building a new string with append or joined.

Substring: a view into another string

Slicing a string does not copy the text. It gives you a Substring, a window that shares the original storage. That makes split and prefix cheap even on very large text, but it comes with a rule: a Substring keeps the whole original string alive in memory. Convert it with String(...) when you want to store it for a long time.

Swift Substring and String

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Functions that take String do not accept a Substring, which is intentional: the explicit String(part) makes you decide to copy. If you write functions that should accept both, declare the parameter as some StringProtocol; the lesson Slices and Views goes into the memory details.

Pitfalls and good practice

  • Do not index with integers. If you need to loop over characters, use for ch in text. If you need positions, use enumerated() or indices.
  • Do not equate count with bytes. Ask utf8.count when a limit is measured in bytes.
  • Do not build large strings with + in a loop if you can avoid it; append or joined(separator:) on an array of pieces is clearer and faster.
  • Compare strings with ==, not by looking at count or scalars; canonical equivalence is handled for you.
  • Use raw strings for regular expressions and paths, so backslashes stay readable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can't you write text[3] to get the fourth character of a Swift String?

    A Character is a grapheme cluster that may be built from several scalars and bytes, so a position cannot be found with simple arithmetic. Swift uses String.Index and index(_:offsetBy:).
  2. 2. What does "cafe\u{301}".count return?

    The letter e and the combining accent form one grapheme cluster, so the string has 4 Characters even though it has 5 scalars and 6 UTF-8 bytes.
  3. 3. What type does "a=b".split(separator: "=") produce its elements as?

    split returns an array of Substring values that share the original storage. Wrap one in String(...) to get an independent copy.
  4. 4. In the multiline literal, what decides how much indentation is stripped from each line?

    The closing delimiter's indentation is removed from every line; each line must be indented at least that much.
  5. 5. When is a raw string such as #"..."# the better choice?

    In a raw string, backslashes and quotes have no special meaning (only #( ) and similar escapes with the matching number of # do), so patterns and paths stay readable.

Summary

  • String is a Unicode-aware value type; assignment copies, + and append build new text.
  • Character is a grapheme cluster, so count matches what a reader sees; unicodeScalars and utf8 expose the lower levels.
  • Positions are String.Index values; use index(_:offsetBy:), firstIndex(of:) and one-sided ranges, and never subscript with an Int.
  • prefix, suffix, dropFirst, split, hasPrefix and contains cover most work without indices.
  • Slices are Substring values that share storage with the original; convert with String(...) to keep them.
  • Multiline literals strip the closing delimiter's indentation, and raw #"..."# strings keep backslashes literal.

Next: String Interpolation and Formatting