How to covert NSMutableOrderedSet to generic array?

János picture János · Nov 22, 2014 · Viewed 7.1k times · Source

I have this for loop, p is a NSManagedObject, fathers is a to-many relationship, so I need to cast NSMutableOrderedSet to [Family] but it does not work, why?

for f in p.fathers as [Family] {
}

enter image description here enter image description here

Answer

Antonio picture Antonio · Nov 22, 2014

You can obtain an array representation of the set via the array property - then you can downcast it to the proper type and assign to a variable:

let families = p.fathers.array as [Family]

but of course you can also use it directly in the loop:

for f in p.fathers.array as [Family] {
    ....
}

Update

A forced downcast is now required using the ! operator, so the code above should be:

let families = p.fathers.array as! [Family]