首页 > 其他 > 详细

Swift_4_闭包(Blocks)

时间:2014-07-21 13:15:37      阅读:272      评论:0      收藏:0      [点我收藏+]

import Foundation

println("Hello, World!")

var arr = [1,2,4,6,74,2]

func hasClosure(list:[Int], v2:Int, cb:(num:Int, v3:Int) ->Bool)  ->Bool{
    
    for item in arr{
        if(cb(num:item, v3:v2)){
            return true;
        }
    }
    return false;
}

var v2 = hasClosure(arr, 82, {
    (num:Int, v3:Int) ->Bool in
    return num >= v3;
    });
println("v2 is \(v2)")



//sort函数  会根据您提供的排序闭包将已知类型数组中的值进行排序。 一旦排序完成,函数会返回一个与原数组大小相同的新数组,该数组中包含已经正确排序的同类型元素
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}

var reversed = sort(names, backwards)
// reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
//闭包版
reversed = sort(names, { (s1: String, s2: String) -> Bool in
    return s1 > s2
    })

//单行
reversed = sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )

//再精简
reversed = sort(names, { s1, s2 in s1 > s2 } )

//极致精简
reversed = sort(names, { $0 > $1 } )

//终极精简
reversed = sort(names, >)

println("reversed is \(reversed)")

//闭包表达式
//{
//    (parameters) -> returnType in
//    statements
//}


Swift_4_闭包(Blocks)

原文:http://blog.csdn.net/yin_xianwei/article/details/38014847

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!