Sorter with multiple conditions in Swift, such as NSSortDescriptor.
let items: [Item] = ...
// Create Sorter for each attribute
let sorterForNum = Sorter<Item>(asc: false) { $0.num }
let sorterForText = Sorter<Item>(asc: true) { $0.text }
// Create Sorter with multiple conditions
let sorter = Sorter([sorterForNum, sorterForText])
// Get sorted result
let result = items.sorted(by: sorter)
/*
result: [
Item(num: 2, text: "a"),
Item(num: 2, text: "b"),
Item(num: 2, text: "c"),
Item(num: 1, text: "a"),
Item(num: 1, text: "b"),
Item(num: 1, text: "c")
]
*/
Default order is ascending.
Sorter<Item>(asc: false) { $0.num } // Pattern 1
Sorter<Item>(asc: true) { $0.num } // Pattern 2
Sorter<Item> { $0.num } // Pattern 3
Sorter<Item> { $0.0.text < $0.1.text }
Sorter([sorter1, sorter2])
Sorter([sorter1, sorter2, sorter3])
...
Sort items by sorter
let result = items.sort(by: sorter)
- Swift 3.0 or later
- iOS 8.0 or later
- Insert
pod 'Sorter'
to your Podfile. - Run
pod install
.
Note: CocoaPods 1.1.0 is required to install Sorter.
Naoto Onagi, naoto.0n2@gmail.com
Sorter is available under the MIT license. See the LICENSE file for more info.