Search code examples
iosswiftcore-datansset

Converting Set to Array?


When retrieving a collection of objects from CoreData via a relationship, swift is giving me an NSSet rather than an array as i would have expected.

Is there a way i can convert the set into an array?

Code:

var updateExercise : UserExercise?

destinationViewController?.userExerciseSets = self.updateExercise?.exercisesets as? [UserExerciseSet]

the cautions are

Cast from 'NSSet?' to unrelated type '[UserExerciseSet]' always fails

Destination VC has the var : var userExerciseSets : [UserExerciseSet]?


Solution

  • You should define your NSManagedObject model as such:

    class UserExercise: NSManagedObject {
       @NSManaged var exercises: Set<Exercise>!
    }
    

    Then when you need an array, you can simply use the Array's constructor that takes a set.

    let exercises = Array(userExercise.exercises)