-
-
Save sketchytech/029c00a74a4217a89797 to your computer and use it in GitHub Desktop.
Swift: Sort subsequent arrays based on the Sorter generated by the first
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
typealias Sorter = Array<AnyObject> -> Array<AnyObject> | |
enum SortType { | |
case Ascending | |
case Descending | |
} | |
extension Array where Element:Comparable { | |
func sorter(sortType:SortType = .Ascending) -> Sorter { | |
// turn array into an array of optionals so that we don't get confused over identical values | |
var array:[Element?] = self.map({$0}) | |
let arraySorted = self.sort(sortType == .Ascending ? {$0 < $1} : {$0 > $1}) | |
var dic2 = [Int:Element]() | |
for a in arraySorted.enumerate() { | |
dic2[a.index] = a.element | |
} | |
var dic3 = [Int:Int]() | |
for i in 0..<self.count { | |
let obj = dic2[i] | |
for a in array.enumerate() { | |
if a.element != nil && a.element! == obj! { | |
dic3[a.index] = i | |
array[a.index] = nil | |
} | |
} | |
} | |
let sorter:Sorter = {(array:Array<AnyObject>) in | |
var a = [AnyObject](count:array.count, repeatedValue:0) | |
for i in 0..<dic3.count { | |
if i < array.count { | |
a[dic3[i]!] = array[i] | |
} | |
} | |
return a | |
} | |
return sorter | |
} | |
} | |
func sortArrays<T:Comparable>(arrays:[[AnyObject]], basedOn:[T], sortType:SortType = .Ascending) -> [[AnyObject]] { | |
let sorter = basedOn.sorter(sortType) | |
var sortedArrays = [[AnyObject]]() | |
for arr in arrays { | |
sortedArrays.append(sorter(arr)) | |
} | |
return sortedArrays | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've written more or less equivalent code using generics:
https://gist.github.com/callionica/289d33bc6ec1629ffd36
I hope you find it useful.
A few things to note: