美文网首页
Swift 4 Closure 闭包

Swift 4 Closure 闭包

作者: 艺术农 | 来源:发表于2018-06-05 14:59 被阅读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)
    
    • 省略return
    multiplyClosure = {(a: Int, b: Int) -> Int in
        a * b
    }
    result = multiplyClosure(4, 3)
    
    • 利用swift的类型推断省略参数类型
    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: +)
    
    • trailing closure syntax
      上面的代码已经够精简了,但是swift提供了另一种办法来简化上面的操作:trailing closure syntax(尾部闭包语法),这种方式是有条件的,只能在函数的最后一个参数为函数类型时,才能使用。
    operateOnNumbers(4, 4){
        $0 + $1
    }
    

    返回值为空的闭包

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

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

    相关文章

      网友评论

          本文标题:Swift 4 Closure 闭包

          本文链接:https://www.haomeiwen.com/subject/dwgpsftx.html