swift 闭包

例子1:

使用sort函数

let names = ["A-a","C","B-b","D"]
let reversed = names.sort(backwards)
func backwards(firstStr: String,secondStr: String) -> Bool {
        return firstStr < secondStr;
    }

例子2:

自定义对象

class Model {
    var name = String();
    var age = String();
    
    init(name: String,age: String){
        self.name = name;
        self.age = age;
    };
    
    
}

let models =   [Model.init(name: "A-a",age: "12"),Model.init(name: "D",age: "11"),Model.init(name: "B-b",age: "21"),Model.init(name: "C-c",age: "19")]
        let nameResult = models.sort { (ml1,ml2) -> Bool in
            return ml1.name < ml2.name;
        }
        
        for ml in nameResult {
            print(ml.name,ml.age);
        }
        
        
        print("------------------")
        
        let ageResult = models.sort { $0.age < $1.age }

        for ml in ageResult {
            print(ml.age,ml.name);
        }

输出
A-a 12
B-b 21
C-c 19
D 11
------------------
11 D
12 A-a
19 C-c
21 B-b


参考:http://www.jianshu.com/p/ad71c94e7bc6

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...