-2

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!

Roi Mulia
  • 5,626
  • 11
  • 54
  • 105
  • 5
    Possible duplicate of [Swift how to sort array of custom objects by property value](http://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – Alexander Sep 30 '16 at 17:13
  • 1
    This code worries me. `class`, `var` and implicitly wrapped optionals are their own code smells, but put together... not good! – Alexander Sep 30 '16 at 17:14
  • @AlexanderMomchliov Thanks for pointing out! I was in a rush, didn't quiet see those small mistakes, And thanks for the link, I guess i haven't search the right search terms. Have a great day! – Roi Mulia Sep 30 '16 at 17:15

1 Answers1

3

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 }
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • 2
    OP asked for Swift 2.3, but I figured I'd add that it's been renamed to `sorted(by:...)` in Swift 3 – Bek Sep 30 '16 at 17:14
  • @Bek Thanks. I don't think it'll matter though, I suspect this question will be closed and deleted soon enough – Alexander Sep 30 '16 at 17:15
  • Hey Alexander I can't close it with anwers tho. I'll just wait for the moderator to close it. Thanks! Have a great day :) – Roi Mulia Sep 30 '16 at 17:17
  • @RoiMulia Can't you just close without moderator? It's usually better not to delete so others searching the same phrases would find here. – mfaani Oct 04 '16 at 18:05
  • I voted to close as a duplicate. When it reached 5 votes (currently at 3), the question will be closed, and has a link to the duplicate post. – Alexander Oct 04 '16 at 19:57