Swiftpack.co - Package - a6delali/SwiftTri

SwiftTri

Build Status

Sort with multiple conditions in Swift, such as NSSortDescriptor.


struct Person {
    let firstName: String
    let lastName: String
    let age: Int
}

let sortCriteria: SortDescriptor<Person> = combine(sortDescriptors: [
  sortDescriptor(key: { $0.firstName }, by: String.localizedStandardCompare),
  sortDescriptor(key: { $0.lastName }, by: String.localizedStandardCompare),
  sortDescriptor(key: { $0.age }, by: >)
])

let colleagues = [
  Person(firstName: "John", lastName: "Doe", age: 31),
  Person(firstName: "John", lastName: "Doe", age: 27),
  Person(firstName: "John", lastName: "Doiny", age: 27)
]

colleagues.sorted(by: sortCriteria)

/*
result: [
    Person(firstName: "John", lastName: "Doiny", age: 27),
    Person(firstName: "John", lastName: "Doe", age: 27),
    Person(firstName: "John", lastName: "Doe", age: 31)
]
*/

Initializer

1. Initialize sort descriptor by comparable attribute

Default order is ascending.

let sortCriteria: SortDescriptor<Person> = sortDescriptor(key: { $0.age }, by: >)
let sortCriteria: SortDescriptor<Person> = sortDescriptor(key: { $0.age }, ascending: false, by: >)
let sortCriteria: SortDescriptor<Person> = sortDescriptor(key: { $0.lastName }, by: String.localizedStandardCompare)

2. Initialize Sorter by multiple conditions

let sortCriteria: SortDescriptor<Person> = combine(sortDescriptors: [
  sortDescriptor(key: { $0.firstName }, by: String.localizedStandardCompare),
  sortDescriptor(key: { $0.lastName }, by: String.localizedStandardCompare),
  sortDescriptor(key: { $0.age }, by: >)
])
...

Sort sequence

Sort items by sort descriptor

let result = colleagues.sorted(by: sortCriteria)

Installation

Swift Package Manager:

dependencies: [
    .package(url: "https://github.com/a6delali/SwiftTri.git")
]

Author

Abdel Ali, a6delalii@gmail.com

License

Sorter is available under the MIT license. See the LICENSE file for more info.

Github

link
Stars: 0
Help us keep the lights on

Dependencies

Used By

Total: 0