An NSSet
can be converted to Array
using set.allObjects()
but there is no such method in the new Set
(introduced with Swift 1.2). It can still be done by converting Swift Set to NSSet and use the allObjects()
method but that is not optimal.
相关问题
- How to get the maximum of more than 2 numbers in V
- “Zero out” sensitive String data in Swift
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
- pick a random item from a javascript array
相关文章
- C#中 public virtual string Category { get; }这么写会报错:
- Numpy matrix of coordinates
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- PHP: Can an array have an array as a key in a key-
- How can I vertically align my status bar item text
In the simplest case, with Swift 3, you can use
Array
'sinit(_:)
initializer to get anArray
from aSet
.init(_:)
has the following declaration:Usage:
However, if you also want to perform some operations on each element of your
Set
while transforming it into anArray
, you can usemap
,flatMap
,sort
,filter
and other functional methods provided byCollection
protocol:The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:
Or, to use the "sorted" method:
It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.
If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:
Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:
I created a simple extension that gives you an unsorted
Array
as a property ofSet
in Swift 4.0.If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.
To use this, just call
call this method and pass your set
Like This :
You can create an array with all elements from a given Swift
Set
simply withThis works because
Set
conforms to theSequenceType
protocol and anArray
can be initialized with a sequence. Example:ADDITION :
Swift has no DEFINED ORDER for Set and Dictionary.For that reason you should use sorted() method to prevent from getting unexpected results such as your array can be like ["a","b"] or ["b","a"] and you do not want this.
TO FIX THIS:
FOR SETS
Result: ["a","b","c"]
Without sorted()
It can be:
simple math : 3! = 6