Skip to content
A concept for sorting in Swift.
Swift Ruby Objective-C
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
Playgrounds/MyPlayground.playground
Sorter.xcodeproj
Sorter.xcworkspace
Sorter
SorterTests
.codebeatignore
.gitignore
.swift-version
.swiftlint.yml
.travis.yml
Gemfile
Gemfile.lock
LICENSE
Podfile
Podfile.lock
README.md
codecov.yml

README.md

Build Status codebeat badge codecov

Sorter

A concept for sorting in Swift.

Example

import Sorter

//MARK: Example model
struct Restaurant {
    let name: String
    let rating: Float
}

//MARK: Example sorts
extension Restaurant {
    static let alphabeticalSort = Sort<Restaurant> {
        $0.name < $1.name
    }
    
    static let ratingSort = Sort<Restaurant> {
        $0.rating > $1.rating
    }
}

let mcdonalds = Restaurant(name: "McDonalds", rating: 5.5)
let tacoBell = Restaurant(name: "Taco Bell", rating: 2.5)
let kfc = Restaurant(name: "KFC", rating: 2.5)
let objects = [tacoBell, kfc, mcdonalds]
let sorts = [Restaurant.ratingSort, Restaurant.alphabeticalSort]

let sortedObjects = Sorter.sort(objects: objects, using: sorts)
// [mcdonalds, kfc, tacobell]

Built in operators

There are a few built in operators that come with Sorter.

public enum SortOperator<T: Comparable>: SortOperatorProtocol {
    case lessThan
    case greaterThan
    
    public var closure: ((T, T) -> Bool) {
        switch self {
            case .lessThan: return { $0 < $1 }
            case .greaterThan: return { $0 > $1 }
        }
    }
}

public func < <T: Comparable>(lhs: T, rhs: T) -> SortResult {
    return SortResult(lhs: lhs, is: SortOperator.lessThan, rhs: rhs)
}

public func > <T: Comparable>(lhs: T, rhs: T) -> SortResult {
    return SortResult(lhs: lhs, is: SortOperator.greaterThan, rhs: rhs)
}

Defining your own is as easy as conforming to the SortOperatorProtocol

public protocol SortOperatorProtocol {
    associatedtype Object: Comparable
    
    var closure: (Object, Object) -> Bool { get }
}
You can’t perform that action at this time.