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

时间:2023-11-22 13:52:44

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

1
2
3
4
var userList = [UserInfo]()
userList.append(UserInfo(name: "张三", phone: "4234"))
userList.append(UserInfo(name: "李四", phone: "1212"))
userList.append(UserInfo(name: "航歌", phone: "3525"))

方法1

1
2
3
4
5
userList.sortInPlace(onSort)
func onSort(s1:UserInfo, s2:UserInfo) -> Bool{
    return s1.name > s2.name
}

方法2

1
userList.sortInPlace({$0.name > $1.name})