zoukankan      html  css  js  c++  java
  • swift--闭包

    1.sorted方法举例闭包的方法

    不用闭包传入方法(String, String) -> Bool.需要有这一样一个方法

      let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

      func backward(_ s1: String, _ s2: String) -> Bool {

          return s1 > s2

      }

      var reversedNames = names.sorted(by: backward)

    利用闭包

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

          return s1 > s2

      })

    根据上下文自动判断类型

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

    隐藏return隐藏返回的类型

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

    参数也可以省略

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

    只留符号作为表达式

      reversedNames = names.sorted(by: >)

    改成尾随包

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

    如果闭包表达式是函数或方法的唯一参数,使用尾随闭包时,可以把 () 省略掉

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

    2.值捕获栗子

    func makeIncrementer(forIncrement amount: Int) -> () -> Int {

        var runningTotal = 0

        func incrementer() -> Int {

            runningTotal += amount

            return runningTotal

        }

        return incrementer

    } 

      let incrementByTen = makeIncrementer(forIncrement: 10)

      incrementByTen()//10

      incrementByTen()//20

      let incrementBySeven = makeIncrementer(forIncrement: 7)

      incrementBySeven()//7

      incrementBySeven()//14

      incrementByTen()//30

    3.逃逸闭包。。这是啥

    4.自动闭包。。没看懂

  • 相关阅读:
    软件测试—— junit 单元测试
    falut error failure 的区别与理解
    错误的反思
    只能在微信浏览器打开的链接,如何查看源码
    PHPManage for IIS Windows 10
    wamp mysql配置
    CSS Flexbox 学习指南、工具与框架
    Android SDK 在线更新镜像服务器资源
    64位win2003 IIS6运行32位的.NET程序
    让服务器iis支持.apk文件下载的设置方法
  • 原文地址:https://www.cnblogs.com/huoran1120/p/6134431.html
Copyright © 2011-2022 走看看