Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSSet to [String] array?

I have an NSSet of Strings, and I want to convert it into [String]. How do I do that?

like image 776
noobprogrammer Avatar asked Jul 27 '15 20:07

noobprogrammer


People also ask

How to convert a set to an array in Java?

Indeed, there are several ways to convert a Set to an Array: using Array.from. let array = Array.from (mySet); Simply spreading the Set out in an array. let array = [...mySet]; The old fashion way, iterating and pushing to a new array (Sets do have forEach) let array = []; mySet.forEach (v => array.push (v));

How to convert set to array in ES6?

Using Set and converting it to an array is very similar to copying an Array... So you can use the same methods for copying an array which is very easy in ES6 For example, you can use ... const a = new Set ( ["Alireza", "Dezfoolian", "is", "a", "developer"]); An array and now you can use all methods that you can use for an array...

Should I use array from myset or TypeScript?

Just wanted to add that [...mySet] has issues when compiled using Typescript (see this issue ), so probably safer to use Array.from (mySet) if you intend to convert to Typescript in the near future. By the way, if anyone is concerned about speed, here's a ranking from fastest to slowest: #1. old-fashioned (forEach/for of); #2.

How to copy an array from one set to another set?

So you can use the same methods for copying an array which is very easy in ES6 For example, you can use ... const a = new Set ( ["Alireza", "Dezfoolian", "is", "a", "developer"]); An array and now you can use all methods that you can use for an array... The code below creates a set from an array and then, using the ... operator.


4 Answers

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

Swift 2

Swift 1

like image 110
Eric Aya Avatar answered Oct 12 '22 05:10

Eric Aya


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)
like image 25
jtbandes Avatar answered Oct 12 '22 06:10

jtbandes


You could do something like this.

let set = //Whatever your set is
var array: [String] = []

for object in set {
     array.append(object as! String)
}
like image 22
Epic Defeater Avatar answered Oct 12 '22 04:10

Epic Defeater


let set = NSSet(array: ["a","b","c"])
let arr = set.allObjects as! [String]
like image 22
orahman Avatar answered Oct 12 '22 05:10

orahman