Swiftly

Swift 5.1 references for busy coders

Strings

Basic string

let myString = "Swift is my favorite programming language!"

String with line breaks

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

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

Multiline string

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

print(myString)
// Output:
// "Swift?
// It's my favorite programming 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 programming 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 programming 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 programming language!"
let newSentence = sentence.replacingOccurrences(of: "Swift", with: "VBA")
print(newSentence) // VBA is my favorite programming language!

Trimming whitespace and new lines with trimmingCharacters(in:)

import Foundation

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

Further reading