在Swift中,闭包是一种自包含的函数代码块,可以在代码中被传递和使用。闭包可以作为函数的参数传递,也可以作为函数的返回值返回。下面是一些在Swift中有效使用闭包的方式:
func operateNumbers(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let result = operateNumbers(a: 5, b: 3, operation: { (num1, num2) in
return num1 + num2
})
print(result) // 输出:8
func operateNumbers(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let result = operateNumbers(a: 5, b: 3) { (num1, num2) in
return num1 - num2
}
print(result) // 输出:2
let addClosure = { (a: Int, b: Int) in
return a + b
}
let result = addClosure(5, 3)
print(result) // 输出:8
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
return {
runningTotal += amount
return runningTotal
}
}
let incrementByTen = makeIncrementer(forIncrement: 10)
print(incrementByTen()) // 输出:10
print(incrementByTen()) // 输出:20