0
0
Swiftprogramming~5 mins

Closure expression syntax in Swift

Choose your learning style9 modes available
Introduction
Closures let you write small blocks of code that you can pass around and run later. They help make your code shorter and easier to read.
When you want to sort a list in a custom way.
When you need to run some code after a task finishes, like downloading a file.
When you want to filter items from a list based on a rule.
When you want to change how a function behaves by giving it a small piece of code.
When you want to handle user actions like button taps in a simple way.
Syntax
Swift
let closureName = { (parameters) -> ReturnType in
    // code here
}
The parameters and return type are optional if Swift can figure them out.
The 'in' keyword separates the parameters from the code inside the closure.
Examples
A closure with no parameters and no return value that prints a greeting.
Swift
let greet = { () -> Void in
    print("Hello!")
}
A closure that takes two numbers and returns their sum.
Swift
let add = { (a: Int, b: Int) -> Int in
    return a + b
}
A shorter closure that multiplies two numbers. Swift infers the return type.
Swift
let multiply = { (a: Int, b: Int) in a * b }
Using a closure with shorthand argument names to double each number in a list.
Swift
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
Sample Program
This program sorts a list of numbers using a closure that compares two numbers and returns true if the first is less than the second.
Swift
let numbers = [5, 3, 8, 1]

// Sort numbers in ascending order using a closure
let sortedNumbers = numbers.sorted { (a: Int, b: Int) -> Bool in
    return a < b
}

print("Sorted numbers:", sortedNumbers)
OutputSuccess
Important Notes
Closures can capture and use variables from the place where they are created.
You can simplify closures by removing types, return keyword, and using shorthand argument names.
Closures are similar to small functions but can be written inline.
Summary
Closures are blocks of code you can pass and run later.
They have a simple syntax with parameters, return type, and 'in' keyword.
Swift lets you write closures in shorter ways when types are clear.