闭包

闭包:Closure、Lambda

  1. 如果闭包类型一定,可以省略返回值类型:
 let cl04: (Int, Int) -> Int = {
    (a: Int, b: Int) in
    return a + b
}
  1. 省略参数的类型:
let cl05: (Int, Int) -> Int = {
    (a, b) in
    return a + b
}
  1. 闭包里的可执行代码只有一句,可以省略return,直接用表达式的结果作为返回值:
let cl06: (Int, Int) -> Int = {
    (a, b) in
    a + b
}
  1. 位置参数 :
let cl07: (Int, Int) -> Int = {
    $0 + $1
}
let newArr01 = arr.sort({
    $0 > $1
})
print(newArr01)
  1. 将闭包作为函数的最后一个参数时,可以写在括号外:
let newArr02 = arr.sort() {
    $0 > $1
}
  1. 如果函数只有一个参数,并且参数为闭包类型时,可以省略圆括号:
let newArr03 = arr.sort {
    $0 > $1
}
  1. 最简单的形式:
let newArr04 = arr.sort(>)
print(newArr04)
  1. 映射:
var arr4 = arr2.map({
    (a: Int) -> String in
    return "\(a)"
})
var arr4 = arr2.map { "\($0 * $0)" }
print(arr4)
  1. 过滤:
var arr5 = arr2.filter({
    (a: Int) -> Bool in
    return a < 3
})
var arr5 = arr2.filter { $0 < 3 }
print(arr5)
  1. 计算数组的和:
var total = arr2.reduce(0, combine: {
    (sum: Int, a: Int) -> Int in
    print(sum, a)
    return sum + a
})
print(total)
  1. 将数组内容变成字符串:
var str = arr2.reduce("", combine: {
    (s: String, a: Int) -> String in
    return s + "\(a)"
})
  1. 求数组中的最大值:
let max = numbers.reduce(0) { (a:Int, b:Int) -> Int in
    if  a > b{
            return a}
    return b
}

print(max)

  1. 函数
    applyKTime 接受整数K和一个闭包作为参数,然后调用闭包K次,闭包满意参数和返回值:(下划线代表参数名)
func applyKTime(K:Int, _ closure:() ->()){
    for _ in 1...K {
        closure()
    }
    }
applyKTime(2, 
    () ->() in
    print("Hi")
} )
applyKTime(3, {
    () -> () in
    print("Hello")
})

你可能感兴趣的:(闭包)