Skip to content

Instantly share code, notes, and snippets.

@ralfebert
Created May 17, 2021 21:11
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 ralfebert/366d89fdc35d76bb9199f0b1b1e86668 to your computer and use it in GitHub Desktop.
Save ralfebert/366d89fdc35d76bb9199f0b1b1e86668 to your computer and use it in GitHub Desktop.
// 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