Swift String Field Notes

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

==========
Rob Kerr
App development for iOS, creating applications for my own development studio (Cuvenx Inc.), and consulting with awesome clients to build their mobile applications.
Ann Arbor, Michigan, USA

Copyright Β© 2021 Rob Kerr