0
0
iOS Swiftmobile~5 mins

Functions and closures in iOS Swift

Choose your learning style9 modes available
Introduction

Functions and closures help you organize your code into reusable blocks. They make your app easier to read and maintain.

When you want to perform a task multiple times without rewriting code.
When you want to pass a small piece of code as a parameter to another function.
When you want to keep your code clean by grouping related actions.
When you want to create quick, temporary functions without naming them.
When you want to handle events like button taps or animations.
Syntax
iOS Swift
func functionName(parameters) -> ReturnType {
    // code to execute
}

let closureName = { (parameters) -> ReturnType in
    // code to execute
}

A function has a name and can be called anywhere in your code.

A closure is like a function without a name and can be stored in variables or passed around.

Examples
This function takes a name and returns a greeting message.
iOS Swift
func greet(name: String) -> String {
    return "Hello, \(name)!"
}
This closure does the same as the function but is stored in a variable.
iOS Swift
let sayHello = { (name: String) -> String in
    return "Hi, \(name)!"
}
This function takes a closure as a parameter and runs it.
iOS Swift
func perform(action: () -> Void) {
    action()
}

perform {
    print("Action performed!")
}
Sample App

This SwiftUI app shows how to use a function and a closure to create greeting messages. The function greet and the closure sayGoodbye both take a name and return a message. The messages are shown on the screen.

iOS Swift
import SwiftUI

struct ContentView: View {
    // Function that returns a greeting
    func greet(name: String) -> String {
        return "Hello, \(name)!"
    }

    // Closure that returns a farewell
    let sayGoodbye = { (name: String) -> String in
        return "Goodbye, \(name)!"
    }

    var body: some View {
        VStack(spacing: 20) {
            Text(greet(name: "Alice"))
                .font(.title)
            Text(sayGoodbye("Bob"))
                .font(.title)
        }
        .padding()
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
OutputSuccess
Important Notes

Functions and closures can capture values from their surroundings, which means they remember variables used inside them.

Closures can be written in a shorter form called trailing closure syntax when passed as the last parameter.

Use descriptive names for functions to make your code easier to understand.

Summary

Functions have names and are reusable blocks of code.

Closures are unnamed functions that can be stored or passed around.

Both help keep your app organized and your code clean.