码迷,mamicode.com
首页 > 其他好文 > 详细

Swift_4_闭包(Blocks)

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

标签:swift

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)

标签:swift

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!