Created
May 17, 2021 21:11
-
-
Save ralfebert/366d89fdc35d76bb9199f0b1b1e86668 to your computer and use it in GitHub Desktop.
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
// based on https://sarunw.com/posts/how-to-sort-by-multiple-properties-in-swift/ | |
struct BlogPost { | |
let title: String | |
let pageView: Int | |
let sessionDuration: Double | |
} | |
extension BlogPost { | |
static var examples: [BlogPost] = [ | |
BlogPost(title: "Alice", pageView: 1, sessionDuration: 3), | |
BlogPost(title: "Peter", pageView: 1, sessionDuration: 2), | |
BlogPost(title: "Kofi", pageView: 1, sessionDuration: 1), | |
BlogPost(title: "Akosua", pageView: 5, sessionDuration: 2), | |
BlogPost(title: "Abena", pageView: 4, sessionDuration: 10) | |
] | |
} | |
extension Array { | |
func sortedByPredicates(_ predicates: [(Element, Element) -> Bool]) -> [Element] { | |
return self.sorted(by: { (lhs, rhs) in | |
for predicate in predicates { | |
if !predicate(lhs, rhs) && !predicate(rhs, lhs) { | |
continue | |
} | |
return predicate(lhs, rhs) | |
} | |
return false | |
}) | |
} | |
} | |
let popularPosts = BlogPost.examples.sortedByPredicates([ | |
{ $0.pageView > $1.pageView }, | |
{ $0.sessionDuration > $1.sessionDuration}, | |
{ $0.title < $1.title } | |
] | |
) | |
dump(popularPosts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment