I'm trying to iterate over an instance of NSOrderedSet. Something like this:
func myFunc() {
var orderedSet = NSOrderedSet(array: [ 42, 43, 44])
for n in orderedSet {
NSLog("%i", n)
}
}
...however the for loop line produces this compiler error:
'NSOrderedSet' does not have a member named 'Generator'
Now I could convert it to an array like this:
for n in orderedSet.array {
NSLog("%i", n)
}
...but I wondered if there was a better solution?
I'm also keen to understand why it's possible to iterate over a set but not an ordered set? NSOrderedSet
implements NSFastEnumeration
, so it should work right?
You can iterate over an ordered set with
UPDATE: As of Swift 1.2 (Xcode 6.3),
NSOrderedSet
conforms toSequenceType
and can be enumerated withfor ... in ...
:The Swifty, simplest, and most general solution would be to shallow copy to an array in O(1) - per the docs. This would allow you to use Swift's other functional techniques and functions.
Simplest, most accessible, O(1) performance: shallow copy to array:
0 1 2 3 4 5 6 7
In general - for other types and cases, you could create a sequence:
0 1 2 3 4 5 6 7
NSOrderedSet
doesn't conform toSequenceType
.NSOrderedSet
is subclass ofNSObject
and notNSSet
as one could imagine. I guess Apple engineers overlooked it.