Swift Functions

Building reusable blocks of code in Swift

🔧 What are Swift Functions?

Functions are reusable blocks of code that perform specific tasks. They help organize your code, avoid repetition, and make programs easier to understand and maintain.


// This is a simple Swift function
func sayHello() {
    print("Hello, World!")
}

// Call the function
sayHello()
                                    

Output:

Hello, World!

Key Function Concepts

📝

Declaration

Use 'func' keyword to create functions

func functionName() {
    // code here
}
🔄

Reusability

Call functions multiple times

func greet() {
    print("Hi!")
}
greet() // Call it
🎯

Purpose

Each function has a specific task

func calculateArea() {
    let area = 5 * 3
    print(area)
}
📋

Organization

Keep code clean and organized

func setupApp() {
    loadData()
    setupUI()
}

🔹 Basic Function Syntax

Every Swift function follows this basic pattern:

func functionName() {
    // Function body
    // Code to execute
}

// Example: A simple greeting function
func welcomeUser() {
    print("Welcome to our app!")
    print("Enjoy your experience!")
}

// Call the function
welcomeUser()

Output:

Welcome to our app!

Enjoy your experience!

🔹 Functions with Different Tasks

Functions can perform various types of tasks:

// Function that displays information
func showAppInfo() {
    print("App Name: Swift Tutorial")
    print("Version: 1.0")
}

// Function that performs calculations
func calculateTip() {
    let bill = 50.0
    let tip = bill * 0.15
    print("Tip amount: $\(tip)")
}

// Function that creates data
func createUserProfile() {
    let username = "SwiftLearner"
    let level = "Beginner"
    print("User: \(username), Level: \(level)")
}

// Call all functions
showAppInfo()
calculateTip()
createUserProfile()

Output:

App Name: Swift Tutorial

Version: 1.0

Tip amount: $7.5

User: SwiftLearner, Level: Beginner

🔹 Why Use Functions?

Functions provide several important benefits:

  • Avoid Repetition: Write code once, use it many times
  • Organization: Break large programs into smaller pieces
  • Readability: Make code easier to understand
  • Testing: Test individual parts of your program
  • Maintenance: Fix bugs in one place
// Without functions (repetitive)
print("Starting task 1...")
print("Task 1 completed!")
print("Starting task 2...")
print("Task 2 completed!")

// With functions (clean)
func completeTask(taskNumber: Int) {
    print("Starting task \(taskNumber)...")
    print("Task \(taskNumber) completed!")
}

completeTask(taskNumber: 1)
completeTask(taskNumber: 2)

🧠 Test Your Knowledge

What keyword is used to declare a function in Swift?