Jason Brady Jason Brady - 3 months ago 14
Swift Question

How cast a NSSet to NSMutableSet in Swift

I am using Core Data in my app and am dealing with a many to many relationship between two entities.
My goal is to have the user select which of one entity will be related to another entity by using a tableview and having the user select cells.

When the Class for the Entity is created, "Lists" is set as type NSSet which makes sense since it doesn't need to be ordered, and I don't want more than one of any other entity in there.

My problem comes when I want to add items to an NSSet, I cannot do it as far as I know without using a NSMutableSet. Then I gain

addObject
and
removeObject
.
I can get everything to work except the part where I initialize the NSMutableSet to have everything that the "Lists" NSSet currently has. Everything I've tried either tells me it will always fail and won't build, or ends up returning nil unexpectedly and errors out.

So is there a way to correctly change the contents of a NSSet or at least cast a NSSet into a NSMutableSet and then when I'm done, cast that NSMutableSet back into a NSSet?

I can add some of my code if necessary, but I think I explained it pretty well.
Let me know and I'll add whatever details you need.

Thank you in advance.

Answer

simply create a mutable copy:

var set = NSSet(objects: "One", "Two", "Three")
let mutableSet = set.mutableCopy() as! NSMutableSet
mutableSet.addObject("Four")
set = mutableSet
Comments