5 Computers make decisions, too!
This chapter introduces how programs make decisions using conditions—questions that evaluate to true or false—and shows how those decisions control what code runs next. You learn the core building blocks of conditional logic in Swift: if, else if, and else, how braces define a block of code that executes when a condition is met, and how comparison operators (==, !=, <, >, <=, >=) let you compare values beyond simple equality. Woven through are everyday analogies (like carrying an umbrella if it’s raining), reminders to test and iterate, and a healthy mindset toward glitches: bugs are opportunities to learn, and patches are how you fix them.
To make these ideas concrete, you build “Which Number is Bigger?”, an app that reads two numbers from text fields and uses if statements to compare them, updating a label with the result. Along the way you connect UI elements to code with IBOutlets and IBActions, convert text input to integers for numeric comparisons, and systematically improve behavior: first handle “greater than,” then patch the “equal” case with else, and finally add else if for the “less than” case so all possibilities are covered. You also practice evaluating conditions, explore operator nuances, and see why careful input handling matters—non-numeric entries crash naïve code—reinforcing the value of testing and incremental fixes.
When many branches make if/else chains messy, you switch to the switch statement for cleaner, faster-to-read code. You use it to map numbers 1–4 to words and apply the same idea in “The Mystery of the Entered Number,” returning a friendly default when input is outside the expected range. Two appsercises extend your skills: “Gold, Silver, Bronze” orders three inputs using nested ifs, and “Times Tables Bee” generates random multiplication questions, checks answers with if, and tracks score, while introducing simple random number generation. By the end, you’ve practiced choosing the right conditional tool, organizing logic clearly, and building small, testable features that turn rules into working apps.
Overview of UI for the Which Number is Bigger app
The Which Number is Bigger app UI elements
Your completed app and output if you use the numbers 8 and 6 as inputs.
The if statement is checking to see if the first number (number1) is greater than the second number (number2).
“Which number is bigger?” App, Trial 1
The Mystery of the Entered Number! App
“The mystery of the entered number” UI
“The mystery of the entered number!” App
A “visual representation” of the idea of the app we are about to create
“Gold, Silver, Bronze” UI
The app, “Gold, Silver, Bronze”
“tTables” UI
The “Times Tables Bee” App
Hello Swift! ebook for free