๐Ÿฆ

Swift Cheat Sheet

Apple's modern language for iOS, macOS, watchOS, and beyond โ€” fast, safe by design (its "optionals" system forces you to handle missing values explicitly), and the only real path into Apple's app ecosystem. Copy-paste examples plus live Run/Submit exercises.

Jump to: Your first programVariablesOptionals if / elseLoopsArrays & dictionariesStructs ๐Ÿš€ Practice problems

Your first program

print("Hello, world!")

Variables

let age = 25          // let = constant, can't change
var name = "Sam"      // var = can change
let price: Double = 19.99

Optionals

Swift's signature safety feature โ€” a value that might be missing must be declared with ?, forcing you to handle the "nothing" case.

var middleName: String? = nil

if let m = middleName {
    print(m)
} else {
    print("no middle name")
}

if / else

let age = 20
if age >= 18 {
    print("Adult")
} else if age >= 13 {
    print("Teen")
} else {
    print("Child")
}

Loops

for i in 0..<5 {
    print(i)
}

var n = 3
while n > 0 {
    print(n)
    n -= 1
}

Arrays & dictionaries

var nums = [10, 20, 30]
nums.append(40)
print(nums[0])          // 10
print(nums.count)      // 4

var ages = ["Sam": 25, "Ana": 30]
print(ages["Sam"]!)   // 25 โ€” force-unwrap since dict lookups are optional
ages["Lee"] = 40

Structs

Swift favors structs (value types) over classes for most everyday data modeling.

struct Dog {
    let name: String
    let age: Int

    func bark() {
        print("\(name) says woof!")
    }
}

// let d = Dog(name: "Rex", age: 3); d.bark()

๐Ÿš€ Practice problems

Full runnable programs, compiled and run in a real Swift sandbox โ€” same workspace as the other cheat sheets.

Sum an array EASY

let nums = [4, 8, 15, 16, 23, 42]
var sum = 0
for n in nums { sum += n }
print(sum)

Reverse a string MEDIUM

func reverseStr(_ s: String) -> String {
    return String(s.reversed())
}

print(reverseStr("swift"))

FizzBuzz MEDIUM

for i in 1...15 {
    if i % 15 == 0 {
        print("FizzBuzz")
    } else if i % 3 == 0 {
        print("Fizz")
    } else if i % 5 == 0 {
        print("Buzz")
    } else {
        print(i)
    }
}

Word frequency with a dictionary HARD

let text = "the cat sat on the mat the cat ran"
var counts: [String: Int] = [:]
for word in text.split(separator: " ") {
    counts[String(word), default: 0] += 1
}
for (word, n) in counts {
    print("\(word): \(n)")
}