美文网首页
关于Swift语言中Closure的简化推导及简单使用

关于Swift语言中Closure的简化推导及简单使用

作者: 闻道刘 | 来源:发表于2018-07-14 05:52 被阅读9次

    《Swift_Apprentice》是一本非常不错的swift入门书籍。
    closure语法对刚入门的时候可能有点难以理解,再加上swift语言的特性,closure可以写得非常简洁,这给新同学造成了暂时的困难,下面我们一起看看在这本书中,它是怎么一步步递进推导closure并帮助我们理解的。

    Shorthand syntax
    Compared to functions, closures are designed to be lightweight. There are many ways to shorten their syntax. First, if the closure consists of a single return statement, you can leave out the return keyword, like so:
    单一返回声明的时候可以忽略return关键字

    multiplyClosure = { (a: Int, b: Int) -> Int in
    a*b }
    

    Next, you can use Swift’s type inference to shorten the syntax even more by removing the type information:
    利用类型推导精简语法

    multiplyClosure = { (a, b) in
    a*b }
    

    Remember, you already declared multiplyClosure as a closure taking two Ints and returning an Int, so you can let Swift infer these types for you.
    And finally, you can even omit the parameter list if you want. Swift lets you refer to each parameter by number, starting at zero, like so:

    multiplyClosure = {
    $0 * $1 }
    

    The parameter list, return type and in keyword are all gone, and your new closure declaration is much shorter than the original. Numbered parameters like this should really only be used when the closure is short and sweet, like the one above. If the parameter list is much longer it can be confusing to remember what each numbered parameter refers to. In these cases you should use the named syntax.

    Consider the following code:

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

    This declares a function named operateOnNumbers, which takes Int values as its first two parameters. The third parameter is named operation and is of a function type. operateOnNumbers itself returns an Int.
    You can then use operateOnNumbers with a closure, like so:

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

    Remember, closures are simply functions without names. So you shouldn’t be surprised to learn that you can also pass in a function as the third parameter of operateOnNumbers, like so:

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

    operateOnNumbers is called the same way, whether the operation is a function or a closure.
    The power of the closure syntax comes in handy again: You can define the closure inline with the operateOnNumbers function call, like this:

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

    There’s no need to define the closure and assign it to a local variable or constant; you can simply declare the closure right where you pass it into the function as a parameter!
    But recall that you can simplify the closure syntax to remove a lot of the boilerplate code. You can therefore reduce the above to the following:

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

    In fact, you can even go a step further. The + operator is just a function that takes
    two arguments and returns one result so you can write:

      operateOnNumbers(4, 2, operation: +)
    

    There’s one more way you can simplify the syntax, but it can only be done when the closure is the final parameter passed to a function. In this case, you can move the closure outside of the function call:

    operateOnNumbers(4, 2) {
    $0 + $1 }
    

    This may look strange, but it’s just the same as the previous code snippet, except you’ve removed the operation label and pulled the braces outside of the function call parameter list. This is called trailing closure syntax.

    OK,能看得懂最好,看不懂就看下面的我自己的经验例子好了。纯手打,如果有手误请指出。

    //声明一个closure属性:
    //()中没有内容,closure没有参数,不需要写Void,但返回值如果没有必须写Void

    var testClosure: (()->Void)?
    

    //在函数中传递一个closure作为参数:
    //String是closure中参数的类型

    func pass(closure: ((String)->Void))
    

    //如果很多常用的,又不想重复写,可以用typealias关键字对类型进行重命名,用起来也很方便,比如上面的testClosure:

    typealias EmptyClosure: (()->Void)
    

    声明就变成这样了:

    var testClosure: EmptyClosure
    

    使用闭包的示范:

    pass(closure:{ _ in
      ///如果不需要使用closure中的形参,可以用"_"进行忽略
    })
    pass(closure:{ text in
      /// text是自己起的名字,随意起。
      print(text)
    })
    pass(closure:{
      /// 如果懒得起名字,但想用这个参数中的值,可以用$0这种来代替,$0代表闭包中第一个形参。$1代表第二个,以此类推。但注意闭包中的in关键字已经没有写出来了,通过编译器隐式推导这是一个闭包。
      print($0)
    })
    

    如果调用的时候有产生循环引用,比如closure和self产生循环引用,通过类似oc里面的weak修饰,调用的时候如下:

    pass(closure: {[weak self] text in 
    
      //前面的问号代表self有可能不存在了,后面的两个问号是对设置的默认值。
      print(self?.description ?? "place holder")
    })
    

    相关文章

      网友评论

          本文标题:关于Swift语言中Closure的简化推导及简单使用

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