2

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]?

1 Answer 1

11

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed, but remember that it's a set for a reason - there is no guarantee of order, and two calls to Array() with the same Set may not return elements ordered the same way...
Correct, there should also be an explicit sort in addition to this if it's used for display in the UI. Good catch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.