Member-only story
Closure in swift
The closure is like a box, where we put some code to perform the task, like: addition, multiplication, etc.
It can store in a constant and variable, pass as an argument to a function. Just like functions, closures can take parameters and return values.
Closures are reference types, just like classes, and can be assigned to constants or variables. This allows you to reuse the closure or pass it around to other functions or objects.
closure can capture and store references to constants and variables for the context in which they are defined (Remember things from their surroundings).
Example:
Let’s see a simple example to understand closures in Swift:
func makeAdder(for number: Int) -> () -> Int {
var total = 0
func adder() -> Int {
total += number
return total
}
return adder
}
let add5 = makeAdder(for: 5)
let add10 = makeAdder(for: 10)
print(add5()) // Output: 5
print(add5()) // Output: 10
print(add10()) // Output: 10
print(add5()) // Output: 15
Example:
// Simple Closure
let addClosure = {
print("")
}
// Closure with two param
let addClosure = { (a: Int, b: Int) in
print("")
}
// Closure with two param and single return
let addClosure = { (a: Int, b: Int) -> Int in
return a + b
}
// Closure with Function parameter
func sayNoon(greet: () -> ()) { // no argument with no return type
greet()
}
// How to call above one
sayNoon {
}
// comples condition…