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
117: The Swift Testing Framework
Imagine you're running a high-end bakery. You have a recipe for a sourdough loaf that usually turns out great, but every now and then, a batch comes out flat or way too salty. You wouldn't just put every loaf in the window and hope for the best; you'd have a "tasting station" in the back. Before any bread leaves the kitchen, you check a few specific things: Is the crust golden? Is the crumb open? Does it smell tangy? If any of those checks fail, you don't ship the bread, and you know exactly which part of the process went wrong.
The new Swift Testing framework is exactly that tasting station for your code. In the past, we relied on XCTest, which felt a bit like filling out a rigid government form. Swift Testing is different. It's designed to be more expressive and integrated directly into the language using macros. Instead of following strict naming conventions (like starting every function with the word "test"), we now use attributes to tell Swift, "Hey, this specific function is a check."
Ditching the XCTest Boilerplate
In the old days, if you wanted to test a function, you had to subclass XCTestCase and name your methods testCalculateTotal(). It was clunky. With the Swift Testing framework, we use the @Test attribute. This tells the compiler that the function is a test case, regardless of what you name it. I personally love this because it lets us use descriptive names that actually explain the intent of the test.
Let's look at a real scenario. Suppose we're building a ShoppingCart that handles a 10% discount if the total is over $100. Here is how we'd write a test for that:
import Testing
struct ShoppingCart {
var items: [Double]
func calculateTotal() -> Double {
let sum = items.reduce(0, +)
return sum > 100 ? sum * 0.9 : sum
}
}
@Suite struct ShoppingCartTests {
@Test("Check that discounts are applied to expensive carts")
func discountApplied() {
let cart = ShoppingCart(items: [60.0, 50.0]) // Total 110
let total = cart.calculateTotal()
#expect(total == 99.0)
}
@Test("Check that no discount is applied to cheap carts")
func noDiscount() {
let cart = ShoppingCart(items: [20.0, 10.0])
let total = cart.calculateTotal()
#expect(total == 30.0)
}
}
Notice the #expect macro. This replaces the old XCTAssertEqual. It's much more flexible because it can take almost any boolean expression. If the expression inside #expect is false, the test fails, and Swift provides a clear breakdown of what the value actually was versus what you expected.
Testing Multiple Scenarios without Repeating Yourself
One of the most annoying parts of testing is when you have five different inputs that should all produce the same kind of result. In XCTest, you'd either write five different functions or a messy for loop that stopped at the first failure. Swift Testing solves this with parameterized tests using the arguments parameter in @Test.
If we want to make sure our ShoppingCart handles various price points correctly, we can pass a list of values directly into the test function:
@Test("Verify totals for various cart amounts", arguments: [
(items: [10.0, 10.0], expected: 20.0),
(items: [50.0, 60.0], expected: 110.0 * 0.9),
(items: [100.0, 1.0], expected: 101.0 * 0.9),
(items: [], expected: 0.0)
])
func checkTotals(items: [Double], expected: Double) {
let cart = ShoppingCart(items: items)
#expect(cart.calculateTotal() == expected)
}
This is a game-changer. Swift will run this function four separate times, treating each pair of inputs and expectations as its own individual test. If the third case fails, the other three still run, and you'll see exactly which input caused the crash. It's like having a tasting panel where every single bite is logged individually.
Organizing with Suites and Tags
When your project grows, you don't want to run 2,000 tests every time you change a single line of code. You can wrap your tests in a @Suite (as I did in the first example) to group related tests. But for more granular control, you can use tags.
By adding tags: .critical or tags: .smokeTest to your @Test attribute, you can filter your test runs in Xcode. I usually tag my heavy integration tests—the ones that hit a database or a network—so I can skip them during a quick local build and only run them in the CI pipeline.
📋 Practical Task
Exercise: Validating a Shipping Cost Engine
You are tasked with testing a ShippingCalculator. The business logic is as follows:
- Orders under 5kg cost $5.00 flat.
- Orders between 5kg and 20kg cost $10.00.
- Orders over 20kg cost $20.00.
- Orders with 0kg or negative weight should throw an error or return a specific sentinel value (for this exercise, return -1.0).
Your Goal: Write a test suite using the Swift Testing framework that verifies these four conditions. You must use at least one parameterized test (using arguments:) to handle the weight brackets and separate @Test functions for the edge cases (like negative weight).
struct ShippingCalculator {
func calculateCost(weight: Double) -> Double {
if weight <= 0 { return -1.0 }
if weight < 5 { return 5.0 }
if weight <= 20 { return 10.0 }
return 20.0
}
}
Ensure your tests use #expect and descriptive names for the test functions.
There are no comments for now.