Swift 6 cheatsheet

Swift 6: Basics and optionals

6 common Swift 6 tasks.

Constants and variables

let is constant and var can change. Types are inferred.

let name = "Ada"
var score = 0
score += 10
print("\(name) scored \(score)")

Handle optionals

Unwrap an optional safely with if let or guard let. ?? supplies a default.

func greet(_ name: String?) -> String {
    guard let name else { return "Hello, stranger" }
    return "Hello, \(name)"
}

let length = nickname?.count ?? 0

Arrays and dictionaries

Collections are value types and use generic syntax.

var numbers = [3, 1, 2]
numbers.append(4)
let ages: [String: Int] = ["Ada": 36, "Grace": 45]
let age = ages["Ada"]   // Int?

Loops and switch

switch must be exhaustive and supports patterns and ranges.

for number in 1...3 { print(number) }

switch score {
case 0..<50: print("low")
case 50...: print("high")
default: break
}

Define functions

Argument labels make calls read like sentences. _ removes a label.

func area(width: Double, height: Double) -> Double {
    width * height
}

let a = area(width: 3, height: 4)

Closures

Pass behavior around. Trailing closure syntax reads cleanly.

let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
let total = numbers.reduce(0, +)
let sorted = names.sorted { $0 < $1 }

Was this page helpful?