Overview

8 Reuse your code – Clean it with Function Detergent!

This chapter introduces functions as the essential tool for reusing and cleaning code in Swift. It motivates the idea with a simple game scenario where duplicating the same logic in multiple places is messy, error‑prone, and hard to maintain. The big idea is to write a block of code once and call it whenever needed, making programs shorter, clearer, and easier to change. You’ll learn how to define functions, call them, send them information, and receive results back so your apps become more flexible and powerful.

The chapter starts with simple functions and the basic syntax for defining and calling them, then moves into parameters as inputs that let a single function do many jobs. It explains how parameter names, order, and data types matter, and shows how functions can accept multiple values to compute results (like adding numbers). Next, it covers return values so functions can hand answers back to the caller, including how to store those results and why every return path must be covered for functions that promise a value. You also see control flow with early returns, boolean results for decision making, and the idea that any valid Swift type can be passed in or returned.

Finally, you apply these ideas in three small apps that highlight functions in action. A Virtual Dice app uses a helper function to generate random numbers between 1 and 6 and updates the interface when a button is tapped. A Rock Paper Scissors game captures the player’s move, generates a random computer move, and determines the winner with a function that returns a true/false result. A Money Denomination app takes a dollar amount and, using step‑by‑step calculations (including rounding to cents), computes the fewest bills and coins needed. Across these projects, functions keep the logic organized, reusable, and easy to test and update.

Painting a picture of a function
Understanding functions
Understanding parts of a function
Function with parameters.
Virtual Dice – The Final App
The Virtual Dice UI
Virtual Dice – The Final App
The “Rock Paper Scissors” UI  
 
Rock Paper Scissors UI
Money Denomination – The Final App.
Money Denomination UI
Money Denomination – The Final App.

FAQ

What is a function and why should I use one?A function is a reusable block of code you write once and call whenever you need it. Functions reduce duplication, keep code clean and readable, and make changes easier because you update logic in one place instead of many.
How do I define and call a simple function in Swift?Define with: func functionName() { /* code */ }. Call it by writing its name with parentheses: functionName(). Example: func sayHello() { print("Hello, iOS!") } then call sayHello().
What are parameters and how do I pass data into a function?Parameters are inputs declared inside the parentheses: func say(printThis: String) { print(printThis) }. You call it by providing the parameter label and value: say(printThis: "Good morning!").
Do I have to include parameter names and keep the same order when calling?Yes. In these examples, argument labels are required and must be in the same order as declared. Labels make calls clearer and help you avoid mixing up values.
When do I use quotes around values I pass to a function?Use quotes for String values (for example, "Hi there"). You do not use quotes for numeric types like Int or Double (for example, num1: 23).
How do I return a value from a function?Specify a return type with -> and use return inside the function. Example: func addNums(num1: Int, num2: Int) -> Int { return num1 + num2 }. Capture the result: let result = addNums(num1: 23, num2: 5).
What happens if a function promises a return value but doesn’t return on every path?Swift shows an error. Every possible path must return a value of the declared type. Fix by adding a return outside the if, or by using if/else so all paths return.
Can I use return to exit a function early?Yes. A return statement ends the function immediately and any code after it won’t run. This is useful for early exits (for example, on a tie in a game) but be sure a value is still returned when the function has a return type.
Which data types can I use for parameters and return values?Any valid Swift type works: String, Int, Double, Bool, and more. In this chapter you saw functions that take and/or return String, Int, Double, and Bool.
How are functions used in the sample apps in this chapter?- Virtual Dice: randDice() returns a random Int from 1 to 6 and the button action calls it twice. - Rock Paper Scissors: type() returns a random move and checkForPlayerWin(...) returns Bool to decide the winner. - Money Denomination: an IBAction computes and updates labels using helper logic to break an amount into bills and coins.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hello Swift! ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hello Swift! ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hello Swift! ebook for free