0
0
Swiftprogramming~30 mins

Nested functions in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Nested functions
📖 Scenario: Imagine you are creating a simple calculator app that can add and multiply numbers. To keep your code organized, you want to use nested functions inside a main function.
🎯 Goal: Build a Swift program that uses nested functions to add and multiply two numbers, then prints the results.
📋 What You'll Learn
Create a main function called calculate that takes two integers as input.
Inside calculate, create a nested function called add that returns the sum of the two numbers.
Inside calculate, create another nested function called multiply that returns the product of the two numbers.
Call both nested functions inside calculate and print their results.
💡 Why This Matters
🌍 Real World
Nested functions help organize code in apps like calculators or games where small helper functions are needed inside bigger functions.
💼 Career
Understanding nested functions is useful for writing clean, readable code in Swift, which is important for iOS app development jobs.
Progress0 / 4 steps
1
Create the main function
Write a function called calculate that takes two parameters: num1 and num2, both of type Int.
Swift
Need a hint?

Use the func keyword to define the function with two Int parameters.

2
Add nested functions for addition and multiplication
Inside the calculate function, write two nested functions: add and multiply. Both take no parameters and return an Int. add returns the sum of num1 and num2. multiply returns the product of num1 and num2.
Swift
Need a hint?

Define add and multiply inside calculate using func. Use return to send back the results.

3
Call nested functions and print results
Still inside calculate, call the nested functions add() and multiply(). Store their results in variables sumResult and productResult.
Swift
Need a hint?

Call the nested functions by their names followed by parentheses, then assign their results to variables.

4
Print the results
Inside calculate, print the values of sumResult and productResult using print. Then, call calculate with num1 = 4 and num2 = 5 outside the function.
Swift
Need a hint?

Use print with string interpolation to show the results. Then call calculate(num1: 4, num2: 5) outside the function.