Swift Strings Cheat Sheet
Constructing Strings
String from Literal
1 let str = "Hello, dog!"
2 let str2 = "Hello, 🐶!"
Including Escaped Characters
1 print("Backslash: \\")
2 print("Tab: \t")
3 print("LF: \nThis is on the next line")
4 print ("CR\r")
5 print("Single Quote: \'")
6 print("Double Quote: \"")
7 print("Unicode Scalar: \u{1F436}")
8
9 // output:
10 Backslash: \
11 Tab:
12 LF:
13 This is on the next line
14 CR:
15 Single Quote: '
16 Double Quote: "
17 Unicode Scalar: 🐶
String Concatenation with + operator
1 let hello = "Hello"
2 let world = "world"
3 let helloWorld = hello + ", " + world + "!"
4
5 var hello2 = "Hello"
6 hello2.append(", world!")
String Indexes & Substrings
Because Swift Strings are inherently Unicode. In Unicode, a single "character" can have more than 1 byte. Swift handles this by calculating string index positions dynamically via properties and functions.
This makes the code more verbose, but once you get used to it, it starts to feel normal...sort of? 🤷🏼♂️.
Using Start and End Indices with offsets
1 var hello = "Hello 🐱. Meet the 🐶!"
2
3 var catText = hello[hello.startIndex..<hello.index(
4 hello.startIndex,
5 offsetBy: 8)]
6 print(catText) // Hello 🐱.
7
8 var dogText = hello[hello.index(
9 hello.endIndex,
10 offsetBy: -11)...]
11
12 print(dogText) // Meet the 🐶!
String Manipulations
Most manipulations will use index methods and properties,.
String Insertion
1 var hello = "Hello 🐱!"
2 hello.insert(contentsOf: ", ",
3 at: hello.index(hello.startIndex, offsetBy: 5))
4
5 print(hello)
6
7 // output
8 Hello, 🐱!
Remove Substring
1 var hello = "Hello 🐱. Meet the 🐶!"
2
3 // Remove the excitement (the cat is not excited)
4 hello.remove(at: hello.index(before: hello.endIndex))
5 print(hello)
Replace Substring with Another String
1 var hello = "Hello 🐱. Meet the 🐶!"
2
3 if let catMessage = hello.range(of: "Hello 🐱") {
4 hello.replaceSubrange(catMessage, with: "Quack Quack, 🐥")
5 }
6
7 print(hello) // Quack Quack, 🐥. Meet the 🐶!
Search for and remove a substring
1 var hello = "Hello 🐱. Meet the 🐶!"
2
3 if let rangeToRemove = hello.range(of: " Meet the 🐶!") {
4 hello.removeSubrange(rangeToRemove)
5 }
6
7 print(hello) // Hello 🐱.
Remove from character to end of string
1 var hello = "Hello 🐱. Meet the 🐶!"
2
3 if let firstPeriod = hello.firstIndex(of: ".") {
4 hello.removeSubrange(firstPeriod..<hello.endIndex)
5 }
6
7 print(hello) // Hello 🐱
Remove before a searched string
1 var hello = "Hello 🐱. Meet the 🐶!"
2
3 if let removeStart = hello.firstIndex(of: "M") {
4 hello.removeSubrange(hello.startIndex..<removeStart)
5 }
6
7 print(hello) // Meet the 🐶!
String Interpolation
1 let date = Date()
2 let number = Double.pi
3
4 let str = "On \(date) the value of pi is \(number)"
5
6 print(str)
7
8 // output
9 On 2021-01-28 19:53:16 +0000 the value of pi is 3.141592653589793
Access String content as an Array of Characters
1 let array = Array("Hello, World") // array is [String.Element]
2 print(array[7])
3
4 // output
5 W
6
7 let character = array[2...]
8 print(character)
9
10 // output
11 ["l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]
12
13 let array2 = array.filter { $0 == "l" }
14 print(array2)
15
16 // output
17 ["l", "l", "l"]
String Comparison
Comparisons of equality and order
1 let s1 = "Hello, World!"
2 let s2 = "Hello, world!"
3
4 print(s1 == s2) // false
5 print(s1.caseInsensitiveCompare(s2) == .orderedSame) // true
6
7 print(s1 < s2) // true
8 print(s1.compare(s2).rawValue) // -1
Case Insensitive Comparisons
1 let s1 = "Hello, World!"
2 let s2 = "Hello, world!"
3
4 print(s1 == s2) // false
5 print(s1.lowercased() == s2.lowercased()) // true
6 print(s1.caseInsensitiveCompare(s2) == .orderedSame) // true
Comparisons of "file like" names
When numbers are embedded in strings, String comparison functions can help resolve the lack of missing zeros
1 let s1 = "Customer Proposal Version 9"
2 let s2 = "Customer Proposal Version 10"
3 print(s2 > s1) // "9" comes after "10" in naiive string ordering
4 print(s1.localizedStandardCompare(s2) == .orderedAscending) // 9 comes before 10 as expected
Related:
caseInsensitiveCompare, localizedCaseInsensitveCompare, localizedCompare, compare, isEqual, hash
Prefix and Suffix Operations
1 let s1 = "Dog days"
2
3 print(s1.hasPrefix("Dog")) // true
4 print(s1.hasSuffix("ys")) // true
C-Style Formatting
String can be used to format strings using C-Style format pattern strings.
1 print(String(format:
2 "Epoch time as decimal number: %.0f",
3 Date().timeIntervalSince1970))
4 // Epoch time as decimal number: 1611871444
5
6 print(String(format:
7 "Customer Name: %@ owes %10.2f USD",
8 "ACME, Inc.", 3457.212))
9
10 // Customer Name: ACME, Inc. owes 3457.21 USD
11
12 print(String(format:
13 "Customer Name: %@ owes %-10.2f USD",
14 "ACME, Inc.", 3457.212))
15
16 // Customer Name: ACME, Inc. owes 3457.21 USD
Follow this link for Apple's C-style String Format Specifiers
NSString Interoperability
This is needed less and less than it was years ago, but is still supported:
1 let hello = "Hello, world!" // a String object
2 let nsHello = hello as NSString // an NSString object
Multi-Line Strings
Three consecutive quotation marks signal the beginning of a string, which begins on the following line. Matching three quotation marks finish the string.
- Single quotation marks can be embedded in the string without escaping them
- The line feeds in the string are preserved
1 var oneString = """
2 The quick brown "fox" jumps
3 over the lazy dog
4
5 """
6
7 print("==========")
8 print(oneString)
9 print("==========")
10
11 // Output:
12 ==========
13 The quick brown "fox" jumps
14 over the lazy dog
15
16 ==========
Controlling indentation of the multi-line string
The column position of the ending triple quotation mark defines the indentation for the entire string.
1 let oneString = """
2 The quick brown "fox" jumps
3 over the lazy dog
4 """
5
6 print("==========")
7 print(oneString)
8 print("==========")
9
10 // Output:
11 ==========
12 The quick brown "fox" jumps
13 over the lazy dog
14
15 ==========