例子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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。