closure

func makeIncrement(amount: Int)- > () - >Int {
    var total = 0
    func increment(a) -> Int {
        total + = amount
        return total
    }
    return increment
}

let incrementByTen = makeIncrement(amount: 10)
print(incrementByTen())
print(incrementByTen())
print(incrementByTen())
Copy the code
  • Escape a closure
    • When a closure is passed as an actual argument to a function, and it is called after the function returns, the closure is said to have escaped. When you declare a function that accepts a closure as a formal argument, you can allow escaping when the formal argument is written ´@escaping to specify the closure
    • One way closures can escape is by being stored in a variable defined outside the function.
  • Automatic closure
    • An automatic closure is a closure that is automatically created to be passed as an actual argument to a function expression. It takes no arguments, and when it is called, it returns the value of the internally packaged expression
    • The advantage of this syntax is that you omit the parentheses surrounding the function-form arguments by writing regular expressions instead of displaying closures
    • Automatic closures allow you to defer processing until its internal code runs until you call it
var names = ["zhangsan"."lisi"."wangwu"."zhangliu"]
let customerProvider = { names.remove(at: 0)}print(names.count)
print(customerProvider()) // Delay processing
print(names.count)

var providers:[()->String] = []

func collectCustomProviders(provider: @autoclosure @escaping() - >String) {
    providers.append(provider)
}

collectCustomProviders(provider: names.remove(at: 0))
collectCustomProviders(provider: names.remove(at: 0))
print(names.count)

for p in providers {
    print(p())
    print(p())
}

print(names.count)

class SomeClass {
    var x: String = "hello"
    func doSomething(a) {
        collectCustomProviders(provider: self.x) // The escape closure needs to be referenced using self}}Copy the code

Higher-order functions

  • map

    • For each element in the original set, replace it with a transformed element to form a new set

  • filter

    • For each primitive in the original set, the decision is made to discard it or put it in the new set

  • reduce

    • For each element in the original set, it applies to the current cumulative result

  • flatmap

    • For sets whose elements are sets, a single level set can be obtained
  • compactMap

    • Filtration control
let numbers = [1.2.4.5.10]
print(numbers.map{ $0 * 10 })
print(numbers.filter{ $0 > 4 })
print(numbers.reduce(100) {$0 + The $1})

let arrayNumbers = [[1.2.3], [4.5.6], [7.8.9]]
print(arrayNumbers.flatMap{ $0.map{ $0 * 10 }})

let names: [String? ]= ["zhangsan"."lisi" , nil."wangwu"]
print(names.count)
print(names.compactMap {$0})print(names.compactMap {$0?.count} )
Copy the code