Swiftly

Swift 5.7 references for busy coders

Strings

Basic string

let myString = "Swift is my favorite language!"

String with line breaks

let myString = "Swift?\nIt's my favorite language!"

print(myString)
// Output:
// "Swift?
// It's my favorite language!"

Multiline string

let myLongString = """
Swift?
It's my favorite language!
"""

print(myString)
// Output:
// "Swift?
// It's my favorite language!"

String length with .count() and .isEmpty

let myString = "Hello world!"
print(myString.count) // 12
print(myString.isEmpty) // false
let emptyString = ""
print(emptyString.count) // 0
print(emptyString.isEmpty) // true

String interpolation with \(stringName)

String interpolation is a more efficient way of combining strings than by adding strings with the + operator.

let name = "Tomoko"
let location = "Sydney"
print("Hi, I'm \(name), from \(location).")
// Output: "Hi, I'm Tomoko, from Sydney."

Search within a String with .contains(_:)

import Foundation

let sentence = "Swift is my favorite language!"

print(sentence.contains("Swift")) // true
print(sentence.contains("my favorite")) // true

print(sentence.contains("swift")) // false
print(sentence.contains("charming")) // false

Case-insensitive search with .contains(_:) or range(of:options:)

import Foundation

let sentence = "Swift is my favorite language!"
print(sentence.lowercased().contains("swift")) // true
print(sentence.range(of: "swift", options: .caseInsensitive) != nil) // true

Find-and-replace with replacingOccurrences(of:with:)

import Foundation

let sentence = "Swift is my favorite language!"
let newSentence = sentence.replacingOccurrences(of: "Swift", with: "VBA")
print(newSentence) // VBA is my favorite language!

Trimming whitespace and new lines with trimmingCharacters(in:)

import Foundation

let sentence = "   Swift is my favorite language!\n\n  "
let newSentence = sentence.trimmingCharacters(in: .whitespacesAndNewlines)
print(newSentence) // Swift is my favorite language!

Further reading