How to use an anonymous function in Swift

2 Answers

0 votes
// Anonymous function = A function with no identifier.

// Anonymous function (closure) that takes two Ints and returns their sum.
// { (a: Int, b: Int) -> Int in a + b }  ← Swift’s full closure syntax.
let add: (Int, Int) -> Int = { (a: Int, b: Int) -> Int in
    a + b
}

// Use the anonymous function
let result = add(10, 20)

print(result)


/*
run:

30

*/

 



answered 13 hours ago by avibootz
0 votes
print({ (a: Int, b: Int) in a + b }(10, 20))


/*
run:

30

*/

 



answered 13 hours ago by avibootz
...