1

I've already read similar questions/answer, but none of it resolve my problem.

I've an object like this

class Chat {
    unreadMessages: Int = 0
    messages: Int = 0
}

Then I have an array of Chat objects, and I need to order it by multiple criteria, first by chat with grater unread messages and then chat with grater total messages.

Es.

  Obj  TotMes Unread  
  Chat A 10 3   
  Chat B  1 0     
  Chat C  4 0   
  Chat D  9 9   

Desidered output:

Chat D  9 9   
Chat A 10 3   
Chat C  4 0  
Chat B  1 0 

I try with this sort alhoritm, but don't seems work:

let sorted = chats.sort({ (c1, c2) -> Bool in   
   if c1.unreadMessages > c2.unreadMessages {
      return true
   }
   if c1.messages > c2.messages {
      return true
   }        
   return false
})

Can someone explain me what is wrong with this?

2
  • You could sort array by using predicate rules Commented Nov 24, 2015 at 8:58
  • Think about it: What should happen if c1.unreadMessages < c2.unreadMessages ? Commented Nov 24, 2015 at 9:01

1 Answer 1

5

You haven't got condition for c1.unreadMessages < c2.unreadMessages that should cover all requirements:

let sorted = chats.sort({ (c1, c2) -> Bool in   
   if c1.unreadMessages > c2.unreadMessages {
      return true
   } else if c1.unreadMessages < c2.unreadMessages {
      return false
   } else if c1.messages > c2.messages {
      return true
   }        
   return false
})
Sign up to request clarification or add additional context in comments.

1 Comment

Damn! Sure I forget one condition.. my fault! Thanks man!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.