I have an NSSet of Strings, and I want to convert it into [String]. How do I do that?
Asked
Active
Viewed 1.4k times
4 Answers
13
I would use map
:
let nss = NSSet(array: ["a", "b", "a", "c"])
let arr = nss.map({ String($0) }) // Swift 2
let arr = map(nss, { "\($0)" }) // Swift 1

Eric Aya
- 69,473
- 35
- 181
- 253
-
swift 2 - says nsset doesn't have a map method and the second one forces me to do as! NSString - but ends up getting some dynamicCastObjCClassUnconditional. So neither of them work for whatever reason – noobprogrammer Jul 27 '15 at 20:20
-
Works for me ([screenshot](https://www.evernote.com/l/AFnfzlnodJtJBIq_wK4tRvGdoCwfTU5_2Ck)). Maybe upgrade Xcode? I'm using 7b4. – Eric Aya Jul 27 '15 at 20:22
-
And here's the [screenshot](https://www.evernote.com/l/AFmdJD9SvyVMYLxPtmGj9aRVz6TolnczF7Q) for the Xcode 6 version. :) – Eric Aya Jul 27 '15 at 20:24
-
Hey Eric! It works - only thing is I actually meant is for it to be an NSSet of "Tag"s with a "name" String field (instead of a NSSet of strings). How would I change the nss.map({ String($0) }) to work for this custom class "Tag"? – noobprogrammer Jul 28 '15 at 21:17
-
@noobprogrammer, he answered your question and you used his solution in the followup question. Please accept this answer by clicking on the checkmark to turn it green. – vacawama Jul 30 '15 at 20:30
9
If you have a Set<String>
, you can use the Array constructor:
let set: Set<String> = // ...
let strings = Array(set)
Or if you have NSSet, there are a few different options:
let set: NSSet = // ...
let strings1 = set.allObjects as? [String] // or as!
let strings2 = Array(set as! Set<String>)
let strings3 = (set as? Set<String>).map(Array.init)

jtbandes
- 115,675
- 35
- 233
- 266
2
You could do something like this.
let set = //Whatever your set is
var array: [String] = []
for object in set {
array.append(object as! String)
}

Epic Defeater
- 2,107
- 17
- 20