0

I'm trying to sort an array of custom struct in swift 4.2. I want to sort it out in such a way that

  1. Objects with true isSelected bool property are always at top and all other objects should be sort by ascending using a property called sortOrder (Int).
  2. Objects with isSelected property should also be sorted by sortOrder (ascending way). So far I was able to achieve the 1st goal but having some problem with the 2nd.

Here's my code:

    myArray.sort { (item1, item2) -> Bool in

        if item1.isSelected ?? false && item2.isSelected == false  {
      return true
    } else if item2.isSelected ?? false {
     return false
    }

    return item1. sortOrder < item2. sortOrder
      }

Please help with the 2nd objective. Thank you.

1 Answer 1

2

To sort the array in place:

myArray.sort { item1, item2 in 
   if item1.isSelected == item2.isSelected {
      return item1.sortOrder < item2.sortOrder 
   }
   return item1.isSelected && !item2.isSelected 
}

To get a new sorted array

let sortedArray = myArray.sorted { item1, item2 in 
   if item1.isSelected == item2.isSelected {
      return item1.sortOrder < item2.sortOrder 
   }
   return item1.isSelected && !item2.isSelected 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer mate!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.