Swift - 数组排序方法(附样例)

2020-07-14  本文已影响0人  小驴拉磨

下面通过一个样例演示如何对数组元素进行排序。数组内为自定义用户对象,最终要实现按用户名排序,数据如下:

var peopleList = [People]()
peopleList.append(People(name: "张三", phone: "13322223333"))
peopleList.append(People(name: "李四", phone: "15544442222"))
peopleList.append(People(name: "小驴", phone: "18888888888"))

根据名字排序

//1. 使用sort方法和闭包对数组进行排序
peopleList.sort(by: {(s1: People, s1: People) -> Bool in return s1.name > s2.name })

//2. 可以不用指定参数类型,编译器会帮我们判断
peopleList.sort(by: {(s1, s1) in
    return s1.name > s2.name
})

//3. 可以省略参数名,直接根据数字来引用参数
peopleList.sort(by: {
    return $0.name > $1.name
})

//4. 如果闭包只有一行代码,可以省略return
peopleList.sort(by: {
    $0.name > $1.name
})

//5. 如果闭包是函数调用的最后一个参数,可以将闭包放到括号外面,提高代码的可读性
peopleList.sort(){
    $0.name > $1.name
}

//6. 换行也是可选的,代码可以继续简洁
peopleList.sort(){$0.name > $1.name}
上一篇下一篇

猜你喜欢

热点阅读