Swift 4 Closure 闭包

2018-06-05  本文已影响22人  艺术农

闭包的定义

A closure is simply a function with no name; you can assign it to a variable and pass it around like any other value.

闭包就是简化的函数,只是没有函数名称。你可以把闭包赋值给其他变量,也可以像其他值一样传递。

闭包基础

var multiplyClosure: (Int, Int) -> Int
multiplyClosure = { (a: Int, b: Int) -> Int in
  return a * b
}
let result = multiplyClosure(4, 2)
multiplyClosure = {(a: Int, b: Int) -> Int in
    a * b
}
result = multiplyClosure(4, 3)
multiplyClosure = { (a, b) in
    a * b
}
result = multiplyClosure(4, 4)
multiplyClosure = {
    $0 * $1
}
result = multiplyClosure(4, 5)

闭包和函数的比较

看下下面的代码,其中第三个参数是函数类型

func operateOnNumbers(_ a: Int, _ b: Int,
                      operation: (Int, Int) -> Int) -> Int {
  let result = operation(a, b)
  print(result)
  return result
}

如果我们和闭包结合使用就是下面这样:

let addClosure = { (a: Int, b: Int) -> Int in
    a + b
}
operateOnNumbers(4, 4, operation: addClosure)

和函数结合使用就是这样:

func addFunction (_ a: Int, _ b: Int) -> Int {
    return a + b
}

operateOnNumbers(4, 4, operation: addFunction)

上面的代码也就验证了我们开始所说的,其实闭包就是简化了的没有名字的函数。当然,上面的代码还不够完美,我们还可以利用闭包的简化特性来进一步简化代码。

我们可以直接将闭包传递进函数的参数中,而不需要事先用一个变量来接收:

operateOnNumbers(4, 4, operation: {(a: Int, b:Int) -> Int in
    return a + b
})

还可以更简化:

operateOnNumbers(4, 4, operation: { $0 + $1 })

在swift中运算操作符也是一个函数,所以我们可以进一步简化:

operateOnNumbers(4, 4, operation: +)
operateOnNumbers(4, 4){
    $0 + $1
}

返回值为空的闭包

使用Void来表示返回值为空,其实Void就是()的别名,所以在闭包中指明返回值为Void或者()都是一样的。但是,在函数中你不能这么做,函数的参数列表必须要包围在括号里,像 Void -> () 或者 Void -> Void 都是无效的。

let voidClosure: () -> Void = {
    print("Swift Apprentice is awesome!")
}
voidClosure()
上一篇 下一篇

猜你喜欢

热点阅读