Convert Swift Set to NSMutableSet
Asked Answered
P

1

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.

Peruse answered 27/2, 2018 at 20:26 Comment(4)
Don't do that. Don't use NSMutable... collection types in Swift at all. Set with var is mutable for free (and type safe).Funches
@Funches needed to store in NSUserDefaults, for examplePeruse
I doubt that. NS(Mutable)Set is not a property list compliant typeFunches
@vadian: yup, you're right. Turns out I was looking at NSKeyValueCoding methods instead.Peruse
P
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)
Peruse answered 27/2, 2018 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.