zoukankan      html  css  js  c++  java
  • swift语言点评四-Closure

    总结:整个Closure的作用在于简化语言表述形式。

    一、闭包的简化

    Closure expression syntax has the following general form:

    • { () -> in
    •     }
    • reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    •     return s1 > s2
    • })

    Because the sorting closure is passed as an argument to a method, Swift can infer the types of its parameters and the type of the value it returns. 

    reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )

    Implicit Returns from Single-Expression Closures

    reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

    Shorthand Argument Names

    Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.

    reversedNames = names.sorted(by: { $0 > $1 } )

    Operator Methods

    reversedNames = names.sorted(by: >)

    二、拖尾变换

    • func someFunctionThatTakesAClosure(closure: () -> Void) {
    •     // function body goes here
    • }
    •  
    • // Here's how you call this function without using a trailing closure:
    •  
    • someFunctionThatTakesAClosure(closure: {
    •     // closure's body goes here
    • })
    •  
    • // Here's how you call this function with a trailing closure instead:
    •  
    • someFunctionThatTakesAClosure() {
    •     // trailing closure's body goes here
    • }

    闭包的实现在函数参数列表外;

    再次精简

    reversedNames = names.sorted() { $0 > $1 }

    reversedNames = names.sorted { $0 > $1 }

    完全移出

    • let strings = numbers.map { (number) -> String in
    •     var number = number
    •     var output = ""
    •     repeat {
    •         output = digitNames[number % 10]! + output
    •         number /= 10
    •     } while number > 0
    •     return output
    • }

    Closures Are Reference Types

    Whenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function or closure.

    Escaping Closures

    异步解决方案

    Autoclosures

    表达式语句

    • // customersInLine is ["Ewa", "Barry", "Daniella"]
    • func serve(customer customerProvider: @autoclosure () -> String) {
    •     print("Now serving (customerProvider())!")
    • }
    • serve(customer: customersInLine.remove(at: 0))
    • // Prints "Now serving Ewa!"
  • 相关阅读:
    ParksLink修改密码
    ORA-01940:无法删除当前已链接的用户
    imp导入数据的时候报错:ORA-01658: 无法为表空间 MAXDATA 中的段创建 INITIAL 区
    Linux下查看日志用到的常用命令
    大批量数据高效插入数据库表
    线程中断:Thread类中interrupt()、interrupted()和 isInterrupted()方法详解
    CyclicBarrier、CountDownLatch、Callable、FutureTask、thread.join() 、wait()、notify()、Condition
    Mysql全文索引
    Docker 镜像的常用操作
    Docker 入门
  • 原文地址:https://www.cnblogs.com/feng9exe/p/8708866.html
Copyright © 2011-2022 走看看