How to use closure in Swift

4 Answers

0 votes
let x: Int = 10
let y: Int = 20

// This closure captures x and y from the surrounding scope.
let add: () -> Int = {
    x + y
}

let result: Int = add()

print(result)


/*
run:

30

*/

 



answered Jun 3 by avibootz
0 votes
// Closures capture variables by reference

var counter: Int = 0

// Closure capturing and modifying "counter"
let inc: () -> Void = {
    counter += 1
}

inc()
inc()

print(counter)



/*
run:

2

*/

 



answered Jun 3 by avibootz
0 votes
// Closure with parameters

let factor: Int = 3

// Closure capturing "factor"
let multiply: (Int, Int) -> Int = { (a: Int, b: Int) in
    (a + b) * factor
}

print(multiply(5, 5))



/*
run:

30

*/

 



answered Jun 3 by avibootz
0 votes
// Closures inside higher‑order functions

let nums: [Int] = [1, 2, 3]
let factor: Int = 2

// map uses a closure that captures "factor"
let doubled: [Int] = nums.map { $0 * factor }

print(doubled)


/*
run:

[2, 4, 6]

*/

 



answered Jun 3 by avibootz

Related questions

4 answers 39 views
4 answers 33 views
5 answers 39 views
4 answers 35 views
3 answers 33 views
...