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())
  • 相关阅读:
    Maven 打包指定子工程项目(springcloud分模块打包)
    linux常见问题: zip/unzip: command not found
    CentOS8安装jdk1.8
    nacos-docker镜像安装nacos并配置数据库
    浏览器的一个请求从发送到返回都经历了什么
    python之scrapy
    常见的爬虫与反爬虫斗争
    Python闭包与延迟绑定
    ip代理
    python编程:统计文件中单词出现次数
  • 原文地址:https://www.cnblogs.com/miss-once/p/5175355.html
Copyright © 2011-2022 走看看