Skip to content

Swift Cheat Sheet

Swift is a modern, strongly typed programming language for Apple platforms. This Swift cheatsheet is an example-driven reference covering core syntax, optionals, collections, protocols, generics, and concurrency.


Minimal Program

import Foundation

print("Hello, Swift")

Variables & Constants

var a = 10
let b = 20
var c: Int = 30
let d: String = "text"

Basic Types

Int
Double
Float
Bool
String
Character

Optionals

var value: Int? = nil
value = 10
if let v = value {
    print(v)
}
let result = value ?? 0
value!

Strings

let s = "Swift"

s.count
s.uppercased()
s.contains("wi")
let name = "World"
"Hello \(name)"

Operators

a + b
a - b
a * b
a / b
a % b
a == b
a != b
a > b
a < b
a && b
a || b
!a

Control Flow

if

if a > 10 {
    print("large")
} else {
    print("small")
}

switch

switch a {
case 1:
    print("one")
case 2:
    print("two")
default:
    print("other")
}

Loops

for i in 0..<5 {
    print(i)
}
while a > 0 {
    a -= 1
}

Functions

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}
let r = add(2, 3)

Default Parameters

func multiply(_ a: Int, by b: Int = 2) -> Int {
    return a * b
}

Variadic Parameters

func total(_ nums: Int...) -> Int {
    return nums.reduce(0, +)
}

Tuples

let t = (1, "a", true)
let (x, y, z) = t

Arrays

var arr = [1, 2, 3]
arr.append(4)
arr[0]

Dictionaries

var dict = ["a": 1, "b": 2]
dict["a"]
dict["c"] = 3

Iteration

for item in arr {
    print(item)
}
for (k, v) in dict {
    print(k, v)
}

Structs

struct Point {
    var x: Int
    var y: Int
}
var p = Point(x: 10, y: 20)

Struct Methods

extension Point {
    func sum() -> Int {
        x + y
    }
}

Classes

class Counter {
    var value = 0
    func increment() {
        value += 1
    }
}

Inheritance

class Animal {
    func speak() {}
}

class Dog: Animal {
    override func speak() {}
}

Protocols

protocol Logger {
    func log(_ msg: String)
}
class ConsoleLogger: Logger {
    func log(_ msg: String) {
        print(msg)
    }
}

Protocol Extensions

extension Logger {
    func info(_ msg: String) {
        log(msg)
    }
}

Generics

struct Box<T> {
    let value: T
}
let box = Box(value: 10)

Enums

enum Status {
    case ok
    case error
    case loading
}

Pattern Matching

switch value {
case .some(let v):
    print(v)
case .none:
    break
}

Error Handling

enum MyError: Error {
    case fail
}
func mayFail() throws {
    throw MyError.fail
}
do {
    try mayFail()
} catch {
}

Defer

func example() {
    defer {
        print("done")
    }
    print("working")
}

Closures

let square = { (x: Int) -> Int in
    x * x
}
square(5)

Higher-Order Functions

arr.map { $0 * 2 }
arr.filter { $0 > 1 }
arr.reduce(0, +)

Async / Await

func fetchValue() async -> Int {
    return 42
}
let v = await fetchValue()

Tasks

Task {
    let v = await fetchValue()
    print(v)
}

File I/O

import Foundation

let url = URL(fileURLWithPath: "file.txt")
try? "text".write(to: url, atomically: true, encoding: .utf8)
let content = try? String(contentsOf: url)

Date & Time

let now = Date()