https://www.weheartswift.com/closures/swift
//返回值爲 參數爲Int返回值爲Int的閉包 func addTo(adder: Int) -> Int -> Int { return { num in return num + adder } } let addTwo = addTo(2) /* addTwo = (num: Int) -> Int { return num + 2 } */ let result =addTwo(6)
//$0 閉包默認的第一個參數 func greaterThan(comparer:Int) -> Int -> Bool { return {$0 > comparer} } let greaterThan10 = greaterThan(10) greaterThan10(12) greaterThan10(9)
func makeIterator(from start: Int, step: Int) -> () -> Int { var i = start return { let currentValue = i i += step return currentValue } } var iterator = makeIterator(from: 1, step: 1) iterator() // 1 iterator() // 2 iterator() // 3 var anotherIterator = makeIterator(from: 1, step: 3) anotherIterator() // 1 anotherIterator() // 4 anotherIterator() // 7 anotherIterator() // 10
var array = [3, 4, 5] array.sort(by: >) // > is defined as function // sort does not return a new array // the original array has been changed
sum = array.reduce(0, {$0 + $1}) // or sum = array.reduce(0, +) // operators are methods in Swift
let array = [2, 3, 4] /// result is [3, 4, 5] array.map{ $0 + 1}
let array = [2, 3, 4] let newArray = array.filter({ $0 > 3}) //newArray = [4]