2

I have a class defined like this:

class someClass {
   var isCompleted = false
}

how to sort the list of the someClass? if want to move the completed items to the top of the list.

4
  • How big is the list? I think two .filters or even a loop will likely be clearer to reaso about (and likely faster but who cares) Commented Mar 4, 2015 at 6:18
  • @BenjaminGruenbaum You mean filter it and combine the result? Commented Mar 4, 2015 at 6:21
  • Yes, you can also directly sort it but a sort on a boolean is just weird Commented Mar 4, 2015 at 6:22
  • @A-Live Filter it and combine the result, but maybe there are some better ways. Commented Mar 4, 2015 at 6:25

3 Answers 3

7

You can sort according to the boolean property by converting the values to Int:

let arrayOfClasses =  ... // array of classes

let sortedArrayOfClasses = sorted(arrayOfClasses) {
    Int($0.isCompleted) > Int($1.isCompleted)
}

Or with "in-situ" sort:

var arrayOfClasses =  ... // array of classes

sort(&arrayOfClasses) {
    Int($0.isCompleted) > Int($1.isCompleted)
}
Sign up to request clarification or add additional context in comments.

Comments

3

parameter closure for sort or sorted returns true iff the first parameter must be ordered before the second, otherwise false.

So you can:

let array = [ ... ]

let sortedArray = array.sorted { a, b in
    a.isCompleted && !b.isCompleted
}

1 Comment

Works great, thank you! I shortened it to array.sorted { $0.isCompleted && !$1.isCompleted }
0
var yourArrayOfBooleans:[SomeClass] = ...

var sortedArrayOfBooleans:[SomeClass] = []
var tmpArray:[SomeClass] = []

for ar in yourArrayOfBooleans
{
     if ar.isCompleted
     {
          sortedArrayOfBooleans.append(ar)
     }
     else
     {
         tmpArray.append(ar)
     }
}
sortedArrayOfBooleans += tmpArray

Comments

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.