Functions and closures help you organize your code into reusable blocks. They make your app easier to read and maintain.
Functions and closures in 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.
func greet(name: String) -> String {
return "Hello, \(name)!"
}let sayHello = { (name: String) -> String in
return "Hi, \(name)!"
}func perform(action: () -> Void) {
action()
}
perform {
print("Action performed!")
}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.
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() } } }
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.
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.