Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
7: Functions and Closures
I've seen a lot of people trip up when they start treating functions as "first-class citizens" in Swift. By that, I mean the moment you realize you can pass a function into another function just like you'd pass an integer or a string. It's incredibly powerful, but the syntax for closures and function references can feel like a riddle if you aren't expecting a few specific quirks.
Take a look at this. Imagine we're building a simple e-commerce app. We have a Product struct and a function that filters a list of products based on a condition we provide.
struct Product {
let name: String
let price: Double
}
func filterProducts(products: [Product], condition: (Product) -> Bool) -> [Product] {
return products.filter(condition)
}
func isExpensive(product: Product) -> Bool {
return product.price > 100.0
}
let myProducts = [Product(name: "Cable", price: 10.0), Product(name: "Monitor", price: 200.0)]
// ❌ This line causes a compiler error!
let expensiveStuff = filterProducts(products: myProducts, condition: isExpensive)
The Argument Label Trap
If you try to compile this, Swift will scream at you. It'll tell you that it can't convert a function (Product) -> Bool to a closure of type (Product) -> Bool. That sounds insane—they look identical, right? But here is the catch: in Swift, argument labels are part of the function's type signature.
The filterProducts function expects a closure that takes a Product with no label. However, the isExpensive function is defined as taking a Product with the label product:. To the compiler, (Product) -> Bool and (product: Product) -> Bool are completely different types. I've spent way too many hours debugging this exact mistake early in my career.
Stripping the Label for Flexibility
To fix this, we need to tell Swift that the isExpensive function doesn't require a label when it's being called as a closure. We do this using an underscore _ in the function definition. This makes the function "label-less" for the caller.
// ✅ Fixed: Added the underscore to remove the external label
func isExpensive(_ product: Product) -> Bool {
return product.price > 100.0
}
let expensiveStuff = filterProducts(products: myProducts, condition: isExpensive)
// Now it works perfectly.
Writing Closures Inline
While passing existing functions is great, you'll rarely do it that often. Most of the time, you'll write a closure—essentially an anonymous function—directly inside the call. This saves you from polluting your namespace with tiny functions you'll only use once.
You can replace isExpensive with a closure like this:
let cheapStuff = filterProducts(products: myProducts) { product in
return product.price < 20.0
}
Notice two things here. First, I used trailing closure syntax. Since the closure is the last argument in the function call, I can move it outside the parentheses. It's much cleaner and is the standard way we write Swift. Second, the product in keyword is how we name the arguments being passed into the closure.
Capturing Values from the Outside
One of the coolest (and most dangerous) parts of closures is "capturing." A closure can "remember" variables from the environment where it was created, even if that environment is gone. This is how we handle things like network callbacks or button taps in iOS.
Check this out:
func makePriceChecker(threshold: Double) -> (Product) -> Bool {
// This function returns ANOTHER function
return { product in
return product.price > threshold
}
}
let isOverFifty = makePriceChecker(threshold: 50.0)
let isOverThousand = makePriceChecker(threshold: 1000.0)
let result = isOverFifty(Product(name: "Keyboard", price: 60.0)) // true
The closure returned by makePriceChecker "captured" the threshold value. Even after makePriceChecker finished executing, the closure held onto that 50.0. It's a bit like a function with a built-in memory.
📋 Practical Task
Build a Custom Movie Genre Filter
You are building a movie library app. You have a Movie struct with a title and a genre. Your task is to create a flexible filtering system that allows the user to filter movies by any criteria they want.
Requirements:
- Create a
Moviestruct withtitle: Stringandgenre: String. - Write a function called
filterMoviesthat takes an array ofMovieobjects and a closure. The closure should take aMovieand return aBool. - Create an array of at least 4 movies with different genres (e.g., "Sci-Fi", "Drama", "Comedy").
- Call
filterMoviesusing trailing closure syntax to return only the movies that belong to the "Sci-Fi" genre. - Call
filterMoviesagain using a closure that returns movies whose titles have more than 10 characters.
There are no comments for now.