Search code examples
swifttype-conversionsetnsset

Convert Swift Set to NSMutableSet


I can convert from NSMutableSet to Set no problem, but I'm running into problems when doing the reverse.

E.g. this works:

let nsSet = NSMutableSet(array: ["a", "b"])
let swiftSet = nsSet as! Set<String>

But when I try:

let nsSet2 = swiftSet as? NSMutableSet

nsSet2 ends up being nil.


Solution

  • Looks like swift Sets need to be converted to NSSet first:

    let nsSet2 = NSMutableSet(set: set as NSSet)
    

    Or shorthand:

    let nsSet2 = NSMutableSet(set: set)
    

    Or to go from NSSet to Swift Set and back to NSSet:

    let nsSet = NSMutableSet(array: ["a", "b"])
    let set = nsSet as! Set<String>
    let nsSet2 = set as NSSet
    let nsSet3 = NSMutableSet(set: nsSet2)