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

    //闭包的几种书写方式
    
    var names = [13,345,2,323,1,8,21,42,34,32,42,1]
    
    
    // 1
    func compares(args: Int, args2: Int) ->Bool {
    return args > args2
    }
    var names2 = names.sort(compares)
    print(names2)
    
     
    
    
    // 2
    names2 = names.sort({(args: Int, args2: Int) -> Bool in 
    return args < args2
    })
    print(names2)
    
    
    // 3
    
    names2 = names.sort({$0 > $1})
    print(names2)
    
    func customer_fn(cu_fn: ()-> String) {
    let str: String = cu_fn()
    print("customer accpect args for closure : (str)")
    }
    customer_fn({" this is closeure "})
    
    //autoclosure
    func customer_fn(@autoclosure cu_fn: ()-> String) {
    let str: String = cu_fn()
    print("customer accpect args for closure : (str)")
    }
    customer_fn(" this is closeure2 ")
    
    
    //4 此种情况比较特殊,只适用于一句表达式,做比较操作,才可用
    names2 = names.sort(>)
    print(names2)
    
     
    
    //尾随闭包
    
    //使用场景:需要传入一个闭包,并且为最后一个参数时
    names2 = names.sort() { $0 > $1}
    print(names2)
    
    //使用场景: 需要传入一个闭包,有且只有一个参数时
    names2 = names.sort {$0 <= $1}
    print(names2)
    
    
    // 闭包捕获上下文变量,并在生命周期内存储变量值,常例: 嵌套函数种
    func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
    runningTotal += amount
    return runningTotal
    }
    return incrementer
    }
    let increment_fn = makeIncrementer(forIncrement: 10)
    print(increment_fn())
    print(increment_fn())
  • 相关阅读:
    vue 组件
    vue 中的computed和watch
    Vue 框架 笔记
    初次使用git配置以及git如何使用ssh密钥(将ssh密钥添加到github)
    JavaScript 执行机制
    Vue.js 动画
    封装nodeJS中 $on $emit $off 事件
    JS中的事件委托
    什么是“闭包”(closure)为什么要用它?
    js使用面向对象编写下拉菜单
  • 原文地址:https://www.cnblogs.com/miss-once/p/5175355.html
Copyright © 2011-2022 走看看