Learn Swift syntax, optionals, protocols, generics, and memory management.
Swift Language Fundamentals
# No separate install needed - comes with Xcode
# Swift version: swift --versionVariables & Constants
// Constants (immutable) - prefer by default
let maximumLoginAttempts = 3
let π = 3.14159
let welcomeMessage: String = "Hello"
// Variables (mutable)
var currentLoginAttempt = 0
var x = 0.0, y = 0.0, z = 0.0
// Type inference
let meaningOfLife = 42 // Int
let pi = 3.14159 // Double
let name = "Swift" // String
let isAwesome = true // BoolOptionals
// Optional = value or nil
var optionalString: String? = "Hello"
optionalString = nil
// Forced unwrapping (dangerous!)
let forced: String = optionalString! // CRASH if nil
// Safe unwrapping
if let safeString = optionalString {
print(safeString)
}
// Optional chaining
let length = optionalString?.count
// Nil coalescing
let unwrapped = optionalString ?? "Default"
// Guard let (early exit)
func greet(_ name: String?) {
guard let name = name else { return }
print("Hello, \(name)")
}
// Optional map/flatMap
let numbers = ["1", "2", "three"]
let integers = numbers.compactMap { Int($0) } // [1, 2]Control Flow
// For-in loops
for index in 1...5 { print(index) } // 1 to 5 inclusive
for index in 1..<5 { print(index) } // 1 to 4
for _ in 1...3 { print("Hello") } // Ignore value
// While loops
var n = 2
while n < 100 { n *= 2 }
repeat { n *= 2 } while n < 100
// Switch (no implicit fallthrough)
let char = "z"
switch char {
case "a", "e", "i", "o", "u":
print("vowel")
case "z":
print("zee")
default:
print("consonant")
}
// Switch with intervals
let count = 3_000_000_000_000
switch count {
case 0:
print("none")
case 1..<10:
print("few")
case 10..<100:
print("dozens")
default:
print("many")
}
// Switch with tuples
let point = (1, 1)
switch point {
case (0, 0):
print("origin")
case (_, 0):
print("on x-axis")
case (0, _):
print("on y-axis")
case (-2...2, -2...2):
print("near origin")
default:
print("elsewhere")
}Functions
// Basic function
func greet(person: String) -> String {
return "Hello, \(person)!"
}
// Multiple parameters
func greet(person: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return "Hello again, \(person)!"
}
return greet(person: person)
}
// No return value
func printAndCount(string: String) -> Int {
print(string)
return string.count
}
// Ignored return
func printWithoutCounting(string: String) {
let _ = printAndCount(string: string)
}
// Multiple return values (tuple)
func minMax(array: [Int]) -> (min: Int, max: Int)? {
guard !array.isEmpty else { return nil }
var currentMin = array[0]
var currentMax = array[0]
for value in array[1...] {
if value < currentMin { currentMin = value }
if value > currentMax { currentMax = value }
}
return (currentMin, currentMax)
}
// Argument labels & parameter names
func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you're from \(hometown)."
}
// Omit argument label
func greet(_ person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you're from \(hometown)."
}
// Default parameters
func greet(_ person: String, politely: Bool = true) -> String {
politely ? "Hello \(person)" : "Hey \(person)"
}
// Variadic parameters
func arithmeticMean(_ numbers: Double...) -> Double {
numbers.reduce(0, +) / Double(numbers.count)
}
// In-out parameters (pass by reference)
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var x = 1, y = 2
swapTwoInts(&x, &y) // x=2, y=1Closures
// Closure expression syntax
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
// Sorted with closure
let sorted = names.sorted { (s1: String, s2: String) -> Bool in
return s1 < s2
}
// Type inference
let sorted2 = names.sorted { s1, s2 in s1 < s2 }
// Implicit returns
let sorted3 = names.sorted { $0 < $1 }
// Trailing closure
let sorted4 = names.sorted { $0 < $1 }
// Capturing values
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
return {
runningTotal += amount
return runningTotal
}
}
let incrementByTen = makeIncrementer(forIncrement: 10)
incrementByTen() // 10
incrementByTen() // 20Structs & Classes
// Struct (value type)
struct Resolution {
var width = 0
var height = 0
}
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd // Copy!
cinema.width = 2048
print(hd.width) // 1920 (unchanged)
// Class (reference type)
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.frameRate = 25.0
let alsoTenEighty = tenEighty // Same reference!
alsoTenEighty.frameRate = 30.0
print(tenEighty.frameRate) // 30.0
// Identity operators
if tenEighty === alsoTenEighty {
print("Same instance")
}
// Choosing struct vs class
// Use STRUCT for: simple data, copy semantics, thread safety
// Use CLASS for: identity, shared state, inheritanceProperties
struct FixedLengthRange {
var firstValue: Int
let length: Int // Constant property
}
// Computed properties
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
Point(x: origin.x + size.width/2, y: origin.y + size.height/2)
}
set {
origin.x = newValue.x - size.width/2
origin.y = newValue.y - size.height/2
}
}
}
// Property observers
class StepCounter {
var totalSteps: Int = 0 {
willSet { print("About to set to \(newValue)") }
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
// Lazy stored properties
class DataImporter {
var filename = "data.txt"
}
class DataManager {
lazy var importer = DataImporter() // Created on first access
var data = [String]()
}
// Type properties (static)
struct SomeStructure {
static var storedTypeProperty = "Some value"
static var computedTypeProperty: Int { 42 }
}Protocols & Extensions
// Protocol definition
protocol FullyNamed {
var fullName: String { get }
func greet() -> String
}
// Protocol adoption
struct Person: FullyNamed {
var fullName: String
func greet() -> String { "Hello, I'm \(fullName)" }
}
// Protocol with default implementation (extension)
protocol Greetable {
var name: String { get }
func greet() -> String
}
extension Greetable {
func greet() -> String { "Hi, I'm \(name)" }
}
// Protocol composition
protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }
func wishHappyBirthday(to celebrator: Named & Aged) {
print("Happy birthday, \(celebrator.name)! You're \(celebrator.age)!")
}
// Associated types
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
struct IntStack: Container {
var items = [Int]()
mutating func append(_ item: Int) { items.append(item) }
var count: Int { items.count }
subscript(i: Int) -> Int { items[i] }
}
// Generic where clauses
func allItemsMatch<C1: Container, C2: Container>(
_ someContainer: C1,
_ anotherContainer: C2
) -> Bool where C1.Item == C2.Item, C1.Item: Equatable {
if someContainer.count != anotherContainer.count { return false }
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] { return false }
}
return true
}Generics
// Generic function
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
// Generic type
struct Stack<Element> {
var items = [Element]()
mutating func push(_ item: Element) { items.append(item) }
mutating func pop() -> Element { items.removeLast() }
}
// Type constraints
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
for (index, value) in array.enumerated() {
if value == valueToFind { return index }
}
return nil
}
// Associated types with generics
protocol SuffixableContainer: Container {
associatedtype Suffix: SuffixableContainer where Suffix.Item == Item
func suffix(_ size: Int) -> Suffix
}
// Opaque types (Swift 5.1+)
protocol Shape {
func draw() -> String
}
struct Triangle: Shape {
func draw() -> String { "△" }
}
func makeShape() -> some Shape { Triangle() }
// Boxed protocol types (any)
let shapes: [any Shape] = [Triangle(), Square()]Memory Management (ARC)
// Reference counting
class Person {
let name: String
init(name: String) { self.name = name; print("\(name) initialized") }
deinit { print("\(name) deinitialized") }
}
var reference1: Person? = Person(name: "John")
var reference2 = reference1
var reference3 = reference1
reference1 = nil
reference2 = nil
reference3 = nil // "John deinitialized"
// Strong reference cycles
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
var tenant: Person?
deinit { print("Apartment \(unit) deinitialized") }
}
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) deinitialized") }
}
var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john // STRONG REFERENCE CYCLE!
john = nil
unit4A = nil // Neither deinitializes!
// Weak reference (breaks cycle)
class Person {
let name: String
init(name: String) { self.name = name }
weak var apartment: Apartment? // weak
deinit { print("\(name) deinitialized") }
}
// Unowned reference (non-optional, expected to always have value)
class Customer {
let name: String
var card: CreditCard?
init(name: String) { self.name = name }
deinit { print("\(name) deinitialized") }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit { print("Card \(number) deinitialized") }
}
// Closure capture lists (breaking cycles in closures)
class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = { [weak self] in // Capture list
guard let self = self else { return "" }
return "<\(self.name)>\(self.text ?? "")</\(self.name)>"
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit { print("\(name) deinitialized") }
}Error Handling
// Error protocol
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
// Throwing functions
struct Item {
var price: Int
var count: Int
}
class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 11)
]
var coinsDeposited = 0
func vend(itemNamed name: String) throws {
guard let item = inventory[name] else {
throw VendingMachineError.invalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock
}
guard item.price <= coinsDeposited else {
throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
}
coinsDeposited -= item.price
var newItem = item
newItem.count -= 1
inventory[name] = newItem
print("Dispensing \(name)")
}
}
// Handling errors
let machine = VendingMachine()
machine.coinsDeposited = 8
do {
try machine.vend(itemNamed: "Candy Bar")
} catch VendingMachineError.invalidSelection {
print("Invalid selection")
} catch VendingMachineError.outOfStock {
print("Out of stock")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
print("Need \(coinsNeeded) more coins")
} catch {
print("Unexpected error: \(error)")
}
// try? and try!
let result = try? machine.vend(itemNamed: "Chips") // Returns optional
let forced = try! machine.vend(itemNamed: "Pretzels") // Crashes on error
// Defer (cleanup)
func processFile(filename: String) throws {
let file = openFile(filename)
defer { closeFile(file) } // Runs when scope exits
// ... process
}Concurrency (async/await)
// Async function
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
// Calling async function
Task {
do {
let user = try await fetchUser(id: 1)
print(user.name)
} catch {
print("Error: \(error)")
}
}
// Structured concurrency
async func fetchUsers() async throws -> [User] {
async let user1 = fetchUser(id: 1)
async let user2 = fetchUser(id: 2)
async let user3 = fetchUser(id: 3)
return try await [user1, user2, user3]
}
// Task groups
func fetchAllUsers() async throws -> [User] {
try await withThrowingTaskGroup(of: User.self) { group in
for id in 1...100 {
group.addTask { try await fetchUser(id: id) }
}
var users: [User] = []
for try await user in group {
users.append(user)
}
return users
}
}
// Actors (thread-safe state)
actor BankAccount {
var balance = 0
func deposit(_ amount: Int) { balance += amount }
func withdraw(_ amount: Int) -> Bool {
guard balance >= amount else { return false }
balance -= amount
return true
}
}
let account = BankAccount()
Task { await account.deposit(100) }
let balance = await account.balance // Must awaitTry It
Create a playground. Practice optionals, closures, generics. Build a small protocol-oriented example. Test ARC with weak references.
# Create playground in Xcode: File → New → Playground
# Or use Swift REPL: swiftMaster Swift fundamentals
- Write a generic Stack with push/pop/peek
- Create a protocol with associated type and default implementation
- Implement a closure that captures self weakly
- Write async/await network call with error handling
- Build an actor for thread-safe counter
- Fix a strong reference cycle in a Parent/Child class
Swift is type-safe, protocol-oriented, and memory-managed via ARC. Use structs for values, classes for identity. Optionals prevent nil crashes. Generics enable reusable code. async/await makes concurrency readable. Actors protect shared state.
Resources
- Swift Language Guide: https://docs.swift.org/swift-book/
- Swift API Design Guidelines: https://www.swift.org/documentation/api-design-guidelines/
- Swift Concurrency: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/
- Swift Playgrounds: https://www.apple.com/swift/playgrounds/