CODY ← Back to Courses
Swift

Swift — Apple's Modern Programming Language

Swift is a powerful and intuitive programming language for iOS, macOS, watchOS, and tvOS. Developed by Apple, it's designed to be safe, fast, and expressive, combining the best of modern language features.

iOS & macOS Safe & Fast Modern Syntax

What is Swift?

Swift is Apple's modern programming language introduced in 2014. It's designed to be safe, fast, and expressive, with features like optionals, type inference, and powerful functional programming capabilities. Swift is used for developing iOS, macOS, watchOS, and tvOS applications.

📱 Apple Ecosystem

Primary language for all Apple platforms: iOS, iPadOS, macOS, watchOS, tvOS.

🛡️ Safety First

Optionals eliminate null pointer crashes. Memory is managed automatically with ARC.

⚡ Performance

Compiles to native code using LLVM, with performance comparable to C++.

Basic Syntax

Swift syntax is clean and expressive. No semicolons needed, with strong type inference and modern features.

hello world
// This is a comment
import Foundation

// Variables
var name = "Alice"        // Mutable
let age = 25               // Immutable (constant)
let pi: Double = 3.14159   // Explicit type annotation

// String interpolation
print("Hello, \(name)! You are \(age) years old.")

// Type inference
let isActive = true
let numbers = [1, 2, 3, 4, 5]  // Array of Int
let scores = ["Alice": 95, "Bob": 87]  // Dictionary

// If statements
if age >= 18 {
    print("Adult")
} else {
    print("Minor")
}

// Switch statement (powerful, no fallthrough by default)
let grade = 85
switch grade {
case 90...100:
    print("A")
case 80..<90:
    print("B")
default:
    print("C")
}

Optionals — Safe Handling of Missing Values

Optionals represent values that might be nil (absent). Swift forces you to handle nil safely, eliminating null pointer crashes.

optionals
// Optional type (can be nil)
var middleName: String? = "Marie"
middleName = nil  // Allowed

// Unwrapping with if let (safe)
if let name = middleName {
    print("Middle name: \(name)")
} else {
    print("No middle name")
}

// Guard let (early exit)
func greet(_ name: String?) {
    guard let name = name else {
        print("No name provided")
        return
    }
    print("Hello, \(name)!")
}

// Nil coalescing operator (provide default)
let displayName = middleName ?? "Anonymous"

// Optional chaining
let length = middleName?.count  // Returns nil if middleName is nil

// Force unwrap (use carefully!)
let forced = middleName!  // Crashes if nil

// Implicitly unwrapped optional (for IBOutlets)
var button: UIButton!  // Assume it will be set before use

Functions & Closures

Functions are first-class citizens. Closures are self-contained blocks of functionality that can be passed around.

functions and closures
// Basic function
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

// Function with default parameters
func greet(_ name: String, prefix: String = "Hello") -> String {
    return "\(prefix), \(name)!"
}

// Multiple return values (tuple)
func minMax(_ numbers: [Int]) -> (min: Int, max: Int) {
    return (numbers.min() ?? 0, numbers.max() ?? 0)
}

// Variadic parameters
func sum(_ numbers: Int...) -> Int {
    return numbers.reduce(0, +)
}

// Closure expression
let square = { (x: Int) -> Int in
    return x * x
}
print(square(5))  // 25

// Trailing closure syntax
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }  // [2,4,6,8,10]

// Function as parameter (higher-order function)
func repeatTask(times: Int, task: () -> Void) {
    for _ in 1...times {
        task()
    }
}
repeatTask(times: 3) { print("Hello!") }

Structs & Classes

Swift uses structs (value types) and classes (reference types). Structs are preferred for most data modeling.

structs and classes
// Struct (value type) - preferred for most cases
struct Person {
    let name: String
    var age: Int
    
    // Methods
    func greet() -> String {
        return "Hi, I'm \(name)"
    }
    
    // Mutating method (modifies self)
    mutating func haveBirthday() {
        age += 1
    }
}

// Struct with computed properties
struct Rectangle {
    var width: Double
    var height: Double
    
    var area: Double {
        return width * height
    }
    
    var perimeter: Double {
        return 2 * (width + height)
    }
}

// Class (reference type) - for shared state
class BankAccount {
    var balance: Double
    
    init(initialBalance: Double) {
        self.balance = initialBalance
    }
    
    func deposit(_ amount: Double) {
        balance += amount
    }
    
    func withdraw(_ amount: Double) -> Bool {
        guard balance >= amount else { return false }
        balance -= amount
        return true
    }
}

// Usage
var person = Person(name: "Alice", age: 25)
person.haveBirthday()
print(person.age)  // 26

let rect = Rectangle(width: 10, height: 20)
print("Area: \(rect.area)")  // 200

Protocols & Extensions

Protocols define blueprints of methods and properties. Extensions add functionality to existing types.

protocols and extensions
// Protocol definition
protocol Vehicle {
    var make: String { get }
    var model: String { get }
    func start() -> String
}

// Protocol conformance
struct Car: Vehicle {
    let make: String
    let model: String
    
    func start() -> String {
        return "\(make) \(model) engine starts!"
    }
}

// Protocol extension (default implementation)
extension Vehicle {
    func info() -> String {
        return "This is a \(make) \(model)"
    }
}

// Extending existing types
extension Int {
    var squared: Int { return self * self }
    func repeated() -> [Int] {
        return Array(repeating: self, count: self)
    }
}
print(5.squared)  // 25
print(3.repeated())  // [3,3,3]

// Protocol-oriented programming
protocol Identifiable {
    var id: String { get }
}

extension Identifiable {
    func displayID() {
        print("ID: \(id)")
    }
}

struct User: Identifiable {
    let id: String
    let name: String
}

Async/Await — Modern Concurrency

Swift 5.5 introduced structured concurrency with async/await, making asynchronous code easier to write and understand.

async/await
import Foundation

// Simulate network request
func fetchUserData(userId: Int) async throws -> String {
    try await Task.sleep(nanoseconds: 1_000_000_000)  // 1 second
    return "User \(userId) data"
}

// Async function with multiple calls
func fetchAllUsers() async throws -> [String] {
    async let user1 = fetchUserData(userId: 1)
    async let user2 = fetchUserData(userId: 2)
    async let user3 = fetchUserData(userId: 3)
    
    return try await [user1, user2, user3]  // All run in parallel
}

// Task for running async code
func runAsyncExample() {
    Task {
        do {
            let users = try await fetchAllUsers()
            print("Users: \(users)")
        } catch {
            print("Error: \(error)")
        }
    }
}

// Main actor for UI updates (iOS/macOS)
@MainActor
class ViewModel {
    var data: [String] = []
    
    func loadData() async {
        do {
            let users = try await fetchAllUsers()
            self.data = users  // Safe on main actor
        } catch {
            print("Error loading data")
        }
    }
}

// Async sequence (AsyncStream)
func counter() -> AsyncStream<Int> {
    return AsyncStream { continuation in
        Task {
            for i in 1...5 {
                try await Task.sleep(nanoseconds: 500_000_000)
                continuation.yield(i)
            }
            continuation.finish()
        }
    }
}

// Using async sequence
Task {
    for await value in counter() {
        print("Received: \(value)")
    }
}
💡 SwiftUI Integration: Use `@State` and `@ObservableObject` with async/await. Combine framework provides publishers for reactive programming.

🛠 Project: Todo App (SwiftUI)

Build a simple todo list app using SwiftUI with persistent storage.

TodoApp.swift
import SwiftUI

// Model
struct TodoItem: Identifiable, Codable {
    let id = UUID()
    var title: String
    var isCompleted: Bool = false
    let createdAt = Date()
}

// ViewModel
class TodoViewModel: ObservableObject {
    @Published var todos: [TodoItem] = []
    @Published var newTodoTitle: String = ""
    
    private let saveKey = "SavedTodos"
    
    init() {
        loadTodos()
    }
    
    func addTodo() {
        guard !newTodoTitle.isEmpty else { return }
        
        let todo = TodoItem(title: newTodoTitle)
        todos.append(todo)
        newTodoTitle = ""
        saveTodos()
    }
    
    func toggleTodo(_ todo: TodoItem) {
        if let index = todos.firstIndex(where: { $0.id == todo.id }) {
            todos[index].isCompleted.toggle()
            saveTodos()
        }
    }
    
    func deleteTodo(at offsets: IndexSet) {
        todos.remove(atOffsets: offsets)
        saveTodos()
    }
    
    func saveTodos() {
        if let encoded = try? JSONEncoder().encode(todos) {
            UserDefaults.standard.set(encoded, forKey: saveKey)
        }
    }
    
    func loadTodos() {
        guard let data = UserDefaults.standard.data(forKey: saveKey),
              let savedTodos = try? JSONDecoder().decode([TodoItem].self, from: data)
        else { return }
        
        todos = savedTodos
    }
    
    var pendingCount: Int {
        todos.filter { !$0.isCompleted }.count
    }
    
    var completedCount: Int {
        todos.filter { $0.isCompleted }.count
    }
}

// Main View
struct ContentView: View {
    @StateObject private var viewModel = TodoViewModel()
    
    var body: some View {
        NavigationView {
            VStack {
                // Input section
                HStack {
                    TextField("New todo...", text: $viewModel.newTodoTitle)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    
                    Button(action: viewModel.addTodo) {
                        Image(systemName: "plus.circle.fill")
                            .font(.title)
                    }
                    .disabled(viewModel.newTodoTitle.isEmpty)
                }
                .padding()
                
                // Statistics
                HStack {
                    Text("Pending: \(viewModel.pendingCount)")
                        .foregroundColor(.orange)
                    Spacer()
                    Text("Completed: \(viewModel.completedCount)")
                        .foregroundColor(.green)
                }
                .padding(.horizontal)
                
                // Todo list
                List {
                    ForEach(viewModel.todos) { todo in
                        HStack {
                            Image(systemName: todo.isCompleted ? "checkmark.circle.fill" : "circle")
                                .foregroundColor(todo.isCompleted ? .green : .gray)
                                .onTapGesture {
                                    viewModel.toggleTodo(todo)
                                }
                            
                            Text(todo.title)
                                .strikethrough(todo.isCompleted)
                                .foregroundColor(todo.isCompleted ? .gray : .primary)
                            
                            Spacer()
                            
                            Text(todo.createdAt, style: .date)
                                .font(.caption)
                                .foregroundColor(.gray)
                        }
                    }
                    .onDelete(perform: viewModel.deleteTodo)
                }
            }
            .navigationTitle("My Todo List")
        }
    }
}

// Preview
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
🎯 Challenge: Add due dates and priority levels. Implement notifications for overdue tasks. Add categories/tags for todos. Sync with iCloud using CloudKit.