Maik639 Maik639 - 2 years ago 493
Swift Question

Swift: CoreData and generic NSOrderedSet

I'm not sure if I just did not found any information or if it's not possible.

I've looked up several pages. I want to use generic a generic version of the NSOrderedSet in Swift.

With a Set you can do this:

Swift’s Set type is bridged to Foundation’s NSSet class. Source: Apple Docs - Sets

In a NSManagedObject subclass you can simply change the NSSet to Set and it will work. (Tested it)

@property NSArray<NSDate *> *dates;
@property NSSet<NSString *> *words;
@property NSDictionary<NSURL *, NSData *> *cachedData;

var dates: [NSDate]
var words: Set<String>
var cachedData: [NSURL: NSData]

Source: Apple Docs - Lightweight Generics

But I couldn't find any reference to an ordered set in Swift. I could use the NSOrderedSet from Objective-C but I won't have generics in Swift then.

Is there any possibility to define an order in a set in Swift?

Answer Source

No, there is no ordered set in Swift and in all honesty, you shouldn't be using an ordered set period. They are very rarely of use.

But some times, its useful. So you don't have to sort your data by yourself. Especially when you have an entity with a list of sub entities they won't be sorted because it is a set. And then you would have to create a array to have the data prepared in a specific order because a plain set doesn't keep its order. So for core data it is useful especially in use with the NSFetchedResultsController.

It is a lazy addition to Core Data that never should have happened. It is never more useful or more performant than writing your own sort routine. Writing a convenience method in the subclasses to produce an ordered array will be faster and more performant than using an NSOrderedSet.

When you are using an NSFetchedResultsController it is completely useless since the NSFetchedResultsController orders everything for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download