在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