6

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.

Senseful
  • 86,719
  • 67
  • 308
  • 465
  • 1
    Don't do that. Don't use `NSMutable...` collection types in Swift at all. `Set` with `var` is mutable for free (and type safe). – vadian Feb 27 '18 at 20:33
  • @vadian needed to store in NSUserDefaults, for example – Senseful Feb 27 '18 at 21:09
  • I doubt that. `NS(Mutable)Set` is not a property list compliant type – vadian Feb 27 '18 at 21:24
  • @vadian: yup, you're right. Turns out I was [looking at NSKeyValueCoding methods instead](https://stackoverflow.com/a/49018417/35690). – Senseful Feb 27 '18 at 21:44

1 Answers1

7

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)
Senseful
  • 86,719
  • 67
  • 308
  • 465