Search code examples
core-dataswiftios8

Convert NSSet to Swift Array


In CoreData I have defined an unordered to-many relationship. This relationship is defined in Swift like this:

@NSManaged var types : NSMutableSet

However, to use Swift at it's best, I want to use a normal Swift array like Type[]. However, CoreData forces me to use NS(Mutable)Set. How can I type-cast / convert the NSSet to Array<Type>[]?


Solution

  • As of Xcode 7.2 with Swift 2.1.1

    Actually, I found out by trial that:

    @NSManaged var types : Set<Type>
    

    Works perfectly fine.

    The fact is that CoreData generates somethink like:

    @NSManaged var types : NSSet
    

    when creating a NSManagedObject subclass from the editor. So I was wondering if there was a not very verbose method to use the filter method without casting. But then Swift is supposed to bridge automatically between NSSet, NSArray and their counterparts. So I tried declaring it directly as a Set and it works.

    Answering the question, converting it to an Array becomes trivial:

    Array(types)