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.
let closureName = { (parameters) -> ReturnType in // code here }
let greet = { () -> Void in print("Hello!") }
let add = { (a: Int, b: Int) -> Int in return a + b }
let multiply = { (a: Int, b: Int) in a * b }
let numbers = [1, 2, 3, 4] let doubled = numbers.map { $0 * 2 }
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)
let multiply = { (x: Int, y: Int) -> Int in x * y }
print(multiply(3, 4))let greet = { name: String in
print("Hello, \(name)!")
}let numbers = [1, 2, 3, 4]
let doubled = numbers.map({ (num: Int) -> Int in return num * 2 })
print(doubled)Pass the test and this pattern moves unknown