简体   繁体   中英

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.

simply create a mutable copy:

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

mutableCopy()

Call mutableCopy() on your NSSet :

let x = NSSet()
let y = x.mutableCopy() //returns NSMutableSet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM