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.自动闭包。。没看懂

  • 相关阅读:
    Unity 摄像机Clear Flags和Culling Mask属性用途详解
    Unity 坐标系
    Unity 模型导入导出
    Unity 序列化
    正确理解静态Static关键字
    Unity 中的协同程序
    Asp.Net中调用存储过程并返回输出参数
    php学习知识点
    Jauery 中Ajax的几种异步请求
    2014年12月21号面试
  • 原文地址:https://www.cnblogs.com/huoran1120/p/6134431.html
Copyright © 2011-2022 走看看