Created
July 23, 2014 10:00
-
-
Save m1entus/0f697678199771aaa68e to your computer and use it in GitHub Desktop.
Swift generic function sorting by object property
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
func sortByProperty<T: NSObject>(array: [T], property: String, ascending: Bool) -> [T] { | |
var sortedBooks = [T](array) | |
sortedBooks.sort { element1, element2 in | |
var value1: AnyObject! = "" | |
var value2: AnyObject! = "" | |
if element1.respondsToSelector(Selector(property)) { | |
value1 = element1.valueForKey(property) | |
} | |
if element2.respondsToSelector(Selector(property)) { | |
value2 = element2.valueForKey(property) | |
} | |
var result: NSComparisonResult = .OrderedSame | |
if value1 as? String { | |
let string1 = (value1 as String).bridgeToObjectiveC() | |
let string2 = (value2 as String).bridgeToObjectiveC() | |
result = string1.compare(string2) | |
} else if value1 as? NSDate { | |
result = (value1 as NSDate).compare((value2 as NSDate)) | |
} else if value1 as? NSNumber { | |
result = (value1 as NSNumber).compare((value2 as NSNumber)) | |
} | |
if ascending { | |
if result == .OrderedAscending { | |
return true | |
} | |
return false | |
} else { | |
if result == .OrderedAscending { | |
return false | |
} | |
return true | |
} | |
} | |
return sortedBooks | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment