I have an NSSet of Strings, and I want to convert it into [String]. How do I do that?
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));
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...
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.
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.
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
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)
You could do something like this.
let set = //Whatever your set is
var array: [String] = []
for object in set {
array.append(object as! String)
}
let set = NSSet(array: ["a","b","c"])
let arr = set.allObjects as! [String]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With