Search code examples
iosswift3nsset

Swift - Sort the content of NSSSet


I am using Core Data to fetch the list of clinics, the clinics has relations named doctors mapped to Doctor entity.

My issue is, every time I fetch doctors, which is of type NSSSet, the record is fetched randomly, I want to sort it alphabetically using Doctor.name

I tried the following

self.doctorList = clinic.doctors?.sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)])

Where am I going wrong?

Thanks.


Solution

  • (NS)Set is an unordered collection type.

    To order a Set convert it to an array with the allObjects property and sort the array.

    self.doctorList = (clinic.doctors!.allObjects as! [Doctor]).sorted(by: { $0.name < $1.name })
    

    You can even sort the set directly but the result is always an array

    self.doctorList = (clinic.doctors as! Set<Doctor>).sorted(by: { $0.name < $1.name })
    

    And if the set is declared as native Set<Doctor> anyway you can omit the type cast.

    I recommend to declare the doctors relationship as non-optional. If there is no associated doctor the set is empty. But a clinic without any doctor is very unlikely ;-)