Roi Mulia Roi Mulia - 2 months ago 7
Swift Question

Swift - How does one sort an array by internal integer property in the most efficient way

Swift 2.3

Alright folks. Assuming i have a Class named

Post
, and array of Posts,
[Post]
.

Class Posts
{
var message : String!
var scheduledTime : Int!
}
....
var myPosts = [Posts]()...(500 objects)


How can i, in the most efficient/performance wise way(let's assume i have 500
Post
objects inside my array), to sort our
[Post]
array, by our
scheduledTime
(Int) property?

Was always curious on how to approach this kind of questions. Thanks!

Answer

Just use sort(_:) with a closure that compares the first argument's scheduledTime to the second's.

let sortedPosts = myPosts.sort{ $0.scheduledTime < $1.scheduledTime }