Adrian Adrian - 4 years ago 395
Swift Question

How to define the order when sorting a string enum

I have the following enum:

public enum TestEnum: String {
case Day = "Day"
case Week = "Week"
case Month = "Month"
}


This enum is stored in
Core Data
as a
String
. I want to sort my values based on this my enum in the following order:


  • Day

  • Week

  • Month



But because the enum is stored as a
String
, it will sort in the following order:
Day, Month, Week.


My naive approach was to add a
Int
property to the enum and sort based on that:

extension TestEnum {
var sortIndex: Int {

switch self {
case .Day:
return 0
case .Week:
return 1
case .Month:
return 2
}
}
}

func < (lhs: Object, rhs: Object) -> Bool {

return TestEnum(rawValue: lhs.type)?.sortIndex < TestEnum(rawValue: rhs.type)?.sortIndex
}


This doesn't work, the comparison function is never called.

What else can I do to sort this in the order I want ?

Answer Source

A Core Data fetch request cannot sort on a computed property, only on persistent stored properties.

If you want your results to be sorted by Core Data, you'll have to change your model to either include a sort order attribute for the enum, or change the enum type from string to number and reorder the enum values.

If you can't or don't want to change your model, you'll have to sort the results after they've been fetched, however this would be very inefficient (since every object in the results would have to be faulted into memory to compare its enum attribute).

Update:

Here's an example of an entity with a versionOrder attribute that allows Core Data to sort the versions in a different order from the alphabetic versionTitle string.

enter image description here

You could add a sortOrder integer attribute to your model, where .Day = 0, .Week = 1, and .Month = 2, and have Core Data sort the results by that key:

let sortDescriptor = NSSortDescriptor(key: "sortOrder", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download