Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active January 10, 2016 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchytech/32ff1f77037847b5be65 to your computer and use it in GitHub Desktop.
Save sketchytech/32ff1f77037847b5be65 to your computer and use it in GitHub Desktop.
generic secondarySort() function for Swift
enum SortType {
case Ascending, Descending
}
func secondarySort<A: Comparable, B>(arr1:[A], inout arr2:[B], type:SortType = .Ascending) {
var rows = arr1.map{(object1:$0, object2:arr2.removeFirst())}
rows = type == .Ascending ? rows.sort({$0.object1 < $1.object1}) : rows.sort({$0.object1 > $1.object1})
arr2 = rows.map{$0.object2}
}
var Distances = [40,30,10,20]
var IDs = ["f","nc","n","c"]
var Descriptions = ["furthest","not close","nearest","close"]
var Lats = [100.12,88.3,28.07,36.0]
var Longs = [100.12,88.3,28.07,36.0]
secondarySort(Distances, arr2: &IDs)
secondarySort(Distances, arr2: &Descriptions)
secondarySort(Distances, arr2: &Lats)
secondarySort(Distances, arr2: &Longs)
Distances = Distances.sort(<) // [10, 20, 30, 40]
IDs // ["n", "c", "nc", "f"]
Descriptions // ["nearest", "close", "not close", "furthest"]
Lats // [28.07, 36, 88.3, 100.12]
Longs // [28.07, 36, 88.3, 100.12]
// Descending order
secondarySort(Distances, arr2: &IDs, type:.Descending)
secondarySort(Distances, arr2: &Descriptions, type:.Descending)
secondarySort(Distances, arr2: &Lats, type:.Descending)
secondarySort(Distances, arr2: &Longs, type:.Descending)
Distances = Distances.sort(>) // [40, 30, 20, 10]
IDs // ["f", "nc", "c", "n"]
Descriptions // ["furthest", "not close", "close", "nearest"]
Lats // [100.12, 88.3, 36, 28.07]
Longs // [100.12, 88.3, 36, 28.07]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment