0
0
Swiftprogramming~15 mins

Why functions are first-class in Swift - See It in Action

Choose your learning style9 modes available
Why functions are first-class in Swift
📖 Scenario: Imagine you are organizing a small event and want to assign different tasks to helpers. You want to keep track of these tasks and be able to pass them around easily to different people.
🎯 Goal: You will create simple functions representing tasks, store them in a list, and then call them one by one. This will show how functions in Swift can be treated like any other value.
📋 What You'll Learn
Create functions that print simple task messages
Store these functions in an array
Call each function from the array
Print the output of each function call
💡 Why This Matters
🌍 Real World
In real apps, you often pass functions as callbacks or handlers to respond to user actions or events.
💼 Career
Understanding first-class functions is key for Swift developers to write clean, modular, and reusable code.
Progress0 / 4 steps
1
Create simple task functions
Create two functions called taskOne and taskTwo. Each function should print a message: "Task One is done" and "Task Two is done" respectively.
Swift
Need a hint?

Define each function with func keyword and use print inside the function body.

2
Store functions in an array
Create a variable called tasks and assign it an array containing the two functions taskOne and taskTwo.
Swift
Need a hint?

Use square brackets [] to create an array and list the function names without parentheses.

3
Call each function from the array
Use a for loop with variable task to iterate over tasks and call each function inside the loop.
Swift
Need a hint?

Inside the loop, call the function by adding parentheses () after the variable task.

4
Print the final output
Run the program to print the messages from both tasks. The output should show Task One is done and Task Two is done on separate lines.
Swift
Need a hint?

Just run the program. The print statements inside the functions will show the messages.