Swift Strings Cheat Sheet

Constructing Strings

String from Literal

    let str = "Hello, dog!"
    let str2 = "Hello, ๐Ÿถ!"

Including Escaped Characters

    print("Backslash: \\")
    print("Tab: \t")
    print("LF: \nThis is on the next line")
    print ("CR\r")
    print("Single Quote: \'")
    print("Double Quote: \"")
    print("Unicode Scalar: \u{1F436}")
    
    // output:
    Backslash: \
    Tab: 	
    LF: 
    This is on the next line
    CR: 
    Single Quote: '
    Double Quote: "
    Unicode Scalar: ๐Ÿถ

String Concatenation with + operator

    let hello = "Hello"
    let world = "world"
    let helloWorld = hello + ", " + world + "!"
    
    var hello2 = "Hello"
    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

    var hello = "Hello ๐Ÿฑ. Meet the ๐Ÿถ!"
    
    var catText = hello[hello.startIndex..<hello.index(
                                                hello.startIndex,
                                                offsetBy: 8)]
    print(catText) // Hello ๐Ÿฑ.
    
    var dogText = hello[hello.index(
                                hello.endIndex,
                                offsetBy: -11)...]
                                
    print(dogText) // Meet the ๐Ÿถ!

String Manipulations

Most manipulations will use index methods and properties,.

String Insertion

    var hello = "Hello ๐Ÿฑ!"
    hello.insert(contentsOf: ", ", 
            at: hello.index(hello.startIndex, offsetBy: 5))
    
    print(hello)
    
    // output
    Hello,  ๐Ÿฑ!

Remove Substring

    var hello = "Hello ๐Ÿฑ. Meet the ๐Ÿถ!"
    
    // Remove the excitement (the cat is not excited)
    hello.remove(at: hello.index(before: hello.endIndex))
    print(hello)

Replace Substring with Another String

    var hello = "Hello ๐Ÿฑ. Meet the ๐Ÿถ!"
    
    if let catMessage = hello.range(of: "Hello ๐Ÿฑ") {
        hello.replaceSubrange(catMessage, with: "Quack Quack, ๐Ÿฅ")
    }
    
    print(hello) // Quack Quack, ๐Ÿฅ. Meet the ๐Ÿถ!

Search for and remove a substring

    var hello = "Hello ๐Ÿฑ. Meet the ๐Ÿถ!"
    
    if let rangeToRemove = hello.range(of: " Meet the ๐Ÿถ!") {
        hello.removeSubrange(rangeToRemove)
    }
    
    print(hello) // Hello ๐Ÿฑ.

Remove from character to end of string

    var hello = "Hello ๐Ÿฑ. Meet the ๐Ÿถ!"
    
    if let firstPeriod = hello.firstIndex(of: ".") {
        hello.removeSubrange(firstPeriod..<hello.endIndex)
    }
    
    print(hello) // Hello ๐Ÿฑ

Remove before a searched string

    var hello = "Hello ๐Ÿฑ. Meet the ๐Ÿถ!"
    
    if let removeStart = hello.firstIndex(of: "M") {
        hello.removeSubrange(hello.startIndex..<removeStart)
    }
    
    print(hello) // Meet the ๐Ÿถ!

String Interpolation

    let date = Date()
    let number = Double.pi
    
    let str = "On \(date) the value of pi is \(number)"
    
    print(str)
    
    // output
    On 2021-01-28 19:53:16 +0000 the value of pi is 3.141592653589793

Access String content as an Array of Characters

    let array = Array("Hello, World") // array is [String.Element]
    print(array[7])
    
    // output
    W
    
    let character = array[2...]
    print(character)
    
    // output
    ["l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]
    
    let array2 = array.filter { $0 == "l" }
    print(array2)
    
    // output
    ["l", "l", "l"]

String Comparison

Comparisons of equality and order

    let s1 = "Hello, World!"
    let s2 = "Hello, world!"
    
    print(s1 == s2) // false
    print(s1.caseInsensitiveCompare(s2) == .orderedSame) // true
    
    print(s1 < s2) // true
    print(s1.compare(s2).rawValue) // -1

Case Insensitive Comparisons

    let s1 = "Hello, World!"
    let s2 = "Hello, world!"
    
    print(s1 == s2) // false
    print(s1.lowercased() == s2.lowercased()) // true
    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

    let s1 = "Customer Proposal Version 9"
    let s2 = "Customer Proposal Version 10"
    print(s2 > s1) // "9" comes after "10" in naiive string ordering
    print(s1.localizedStandardCompare(s2) == .orderedAscending) // 9 comes before 10 as expected

Related:

caseInsensitiveCompare, localizedCaseInsensitveCompare, localizedCompare, compare, isEqual, hash

Prefix and Suffix Operations

    let s1 = "Dog days"
    
    print(s1.hasPrefix("Dog")) // true
    print(s1.hasSuffix("ys"))  // true

C-Style Formatting

String can be used to format strings using C-Style format pattern strings.

    print(String(format: 
       "Epoch time as decimal number: %.0f", 
                              Date().timeIntervalSince1970))
    // Epoch time as decimal number: 1611871444
    
    print(String(format: 
       "Customer Name: %@ owes %10.2f USD", 
                              "ACME, Inc.", 3457.212))
    
    // Customer Name: ACME, Inc. owes    3457.21 USD
    
    print(String(format: 
       "Customer Name: %@ owes %-10.2f USD", 
                              "ACME, Inc.", 3457.212))
                              
    // 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:

    let hello = "Hello, world!"      // a String object
    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
    var oneString = """
         The quick brown "fox" jumps
         over the lazy dog
    
     """
    
    print("==========")
    print(oneString)
    print("==========")
    
    // Output:
    ==========
        The quick brown "fox" jumps
        over the lazy dog
    
    ==========

Controlling indentation of the multi-line string

The column position of the ending triple quotation mark defines the indentation for the entire string.

    let oneString = """
         The quick brown "fox" jumps
         over the lazy dog
         """
    
    print("==========")
    print(oneString)
    print("==========")
    
    // Output:
    ==========
    The quick brown "fox" jumps
    over the lazy dog
    
    ==========