0

I have objects that are in an array I'd like to sort

let person = Person()
person.isHome = true
person.firstname = "Foo"
person.surname = "Bar"

etc...

I fetch all the people

guard let allPeople = controller.fetchedObjects as? Array<Person> else { return }

Now I'd like to filter and sort

var homeArray = allPeople
        .filter { $0.isHome == true }
        .sort { $0.surname < $1.surname }

All fine... except, what if I want extra 'sort descriptors' like this...

var homeArray = allPeople
        .filter { $0.isHome == true }
        .sort { $0.surname < $1.surname }
        .sort { $0.firstname < $1.firstname }
        .sort { $0.isOut == true && $1.isOut == false }

I still want them ordered by surname, but I also want them sorted by first name after surname and injured above non injured... What is the syntax? I can't seem to find it anywhere... Do I have to go back to using NSArray?

Is it as simple as

.sort { ($0.isOut == true && $1.isOut == false) && ($0.firstname < $1.firstname) && ($0.surname < $1.surname)}
2
  • Change the fetchRequest of NSFetchedResultsController which is much more efficient than manual filtering / sorting Commented Oct 3, 2016 at 11:26
  • What if I can't change the FRC? I know that doesn't make a lot of sense, but the guys I'm working for a framework I have to work within... So I get allPeople and then I must filter and sort after fetching... It's not that there isn't a better way to do this... more that I need the syntax for sorting in this way but with multiple properties Commented Oct 3, 2016 at 11:38

1 Answer 1

1
let new = [person,person1,person2,person3,person4]

var homeInArray = new
.filter { $0.isHome == true &&  $0.isInjured == true }
var homeNINArray = new
.filter { $0.isHome == true &&  $0.isInjured == false }


 var newHomeArray =    homeInArray.sort { $0.firstName < $1.firstName } + homeNINArray.sort { $0.firstName < $1.firstName }

Try it out this solution ...

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry if I confused things with the bool syntax (which might be wrong) I want to sort not only on bools, but multiple conditions.. I've added first name is as well
This is a fair answer to the exact problem I presented though so +1.. but isn't exactly what I need to know

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.