ylliX - Online Advertising Network

Quick tip: How to sort array of objects by given property in custom order in Swift?

Imagine this, you have a class and enum like:

class UserDto {
    public var username: String
    public var userStatus: UserStatusDto
}
enum UserStatusDto: String {
    case ok = "Ok"
    case error = "Error"
}

and you want to sort users by their status, but users with error first. How to do that?

This is quite easy, just extend, or add custom property to UserDto like:

extension UserDto {
    var statusSortOrder: Int { return [UserStatusDto.error, UserStatusDto.ok].firstIndex(of: userStatus) ?? 0 }
}

and now you can just use ordinary sort() or sorted():

sort(by: { $0.statusSortOrder < $1.statusSortOrder })

Leave a Reply