Logo for tanaschita.com

Quick tip on how to unit test Swift optionals with XCTUnwrap

Learn how to shorten if let and guard statements when unit testing.

06 Mar 2023 · 2 min read

When unit testing optionals in Swift, the first idea on how to do that might be to use if let or guard statements combined with the XCTFail assertion method. For example:

func testMixingSmoothies() throws {
let smoothieMaker = SmoothieMaker()
guard let bananaSmoothie = smoothieMaker.makeBananaSmoothie() else {
XCTFail("bananaSmoothie should not be nil")
return
}
}
Sponsorship logo
Architecture & Design Patterns for iOS
This book is a practical guide to essential architectural principles and design patterns for iOS development. It covers strategies for building maintainable apps with Swift and SwiftUI, including dependency injection, navigation, common patterns, and modularization.
LEARN MORE

The XCTest framework actually provides a more elegant solution.

It provides the XCTUnwrap method which attempts to unwrap the optional and throws an error i.e. the test fails if the optional is nil.

func testMixingSmoothies() throws {
let smoothieMaker = SmoothieMaker()
let bananaSmoothie = try XCTUnwrap(smoothieMaker.makeBananaSmoothie())
}

This approach eliminates the need to write repeating XCTFail descriptions. All we need to do is to mark our test function with throws.

Sponsorship logo
Preparing for a technical iOS job interview
Preparing for a technical iOS Job Interview with over 300 questions & answers. Covering Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, iOS File System, Core Data, Concurrency with async/await, Security, Automated Testing, Dependency Management, AI & Machine Learning and more.
LEARN MORE
Sponsorship logo
Architecture & Design Patterns for iOS
This book is a practical guide to essential architectural principles and design patterns for iOS development. It covers strategies for building maintainable apps with Swift and SwiftUI, including dependency injection, navigation, common patterns, and modularization.
LEARN MORE
Sponsorship logo
Become a sponsor of tanaschita.com
By publishing an article on different iOS topics every week, tanaschita.com is constantly growing in the developer community and may provide a great audience for you as a sponsor.
CLICK TO LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

testing

swift

ios

Parameterized tests and test organization with Swift Testing

Learn how to cover multiple inputs with parameterized tests and organize a growing Swift Testing test suite.

21 Sep 2026 · 7 min read

Latest articles and tips

© 2026 tanaschita.com

Privacy policy

Impressum