Getting Started with TDD in Swift
UPDATED FOR SWIFT 4 & XCODE 10
This tutorial will help you write your first TDD app in Swift by building a FizzBuzz game for iOS. We’ll build it up step-by-step with fun challenges along the way and learn about different aspects of building a mobile app.
Who is this tutorial for?
If you’re new to iOS development, Swift or testing in iOS then you should learn a lot from this tutorial.
This tutorial does assume prior programming experience. Specifically you should have an understanding of programming concepts like variables, if statements, functions, and classes.
If you’re a complete beginner to programming in general, you might find a lot of basic programming concepts are skipped over, and for a more gentle start you might want to start elsewhere. I’m a big fan of the Ruby course on Codecademy.
What is Test Driven Development?
Test Driven Development (or TDD to its friends) is a way of writing software. At its core is a simple cycle: Write a test, write as little code as possible to make the test pass, and then refactor (tidy up) the code. It sounds deceptively simple, but it’s a powerful way to write your code.
To learn a bit more about the awesomeness of TDD, @dotariel’s blog post is a good intro.
What are you going to build?
We’ll be building a FizzBuzz game for iOS.
If you haven’t played FizzBuzz before, the rules are pretty simple:
- The aim of the game is to count up as high as you can, starting at 0.
- If the next number is a multiple of 3, tap the “Fizz” button.
- If the next number is a multiple of 5, tap the “Buzz” button.
- If the next number is a multiple of 3 AND 5, tap the “FizzBuzz” button.
We’ll also be adding fun features like a timer, high-scores and changing the numbers.
Notes on Challenges
Throughout the tutorial there are code snippets and challenges — they’re designed to make you think and put in to practice the concepts we’re exploring. I’d recommend that if you want to get the most out of the tutorial resist the urge to copy and paste code and give the challenges a try before peeking at the answers.
Challenges look like this, with links to the answers below.
CHALLENGE 1: Take your first step toward building a tested Swift app. Jump over to Part 1 and get started.
Check your answer here.
If you spot mistakes, or something is unclear please let me know in the comments, or give me a shout on twitter @ynzc.
The completed codebase is available on Github:
If you found this tutorial helpful, please 💚 it below and follow me!