In this case, you should use the simple Antonio solution. I just wanted to discuss this a bit more. If we try to list an instance of 'NSMutableOrderedSet' in a 'for' loop, the compiler will complain:
error: type 'NSMutableOrderedSet' does not conform to the 'SequenceType' protocol
When we write
for element in sequence { // do something with element }
the compiler rewrites it into something like this:
var generator = sequence.generate() while let element = generator.next() {
'NS(Mutable)OrderedSet' does not have a method 'generate()' , that is, it does not comply with the protocol 'SequenceType' . We can change that. First we need a generator:
public struct OrderedSetGenerator : GeneratorType { private let orderedSet: NSMutableOrderedSet public init(orderedSet: NSOrderedSet) { self.orderedSet = NSMutableOrderedSet(orderedSet: orderedSet) } mutating public func next() -> AnyObject? { if orderedSet.count > 0 { let first: AnyObject = orderedSet.objectAtIndex(0) orderedSet.removeObjectAtIndex(0) return first } else { return nil } } }
Now we can use this generator to match the 'NSOrderedSet' 'SequenceType' :
extension NSOrderedSet : SequenceType { public func generate() -> OrderedSetGenerator { return OrderedSetGenerator(orderedSet: self) } }
'NS(Mutable)OrderedSet' can now be used in the 'for' loop:
let sequence = NSMutableOrderedSet(array: [2, 4, 6]) for element in sequence { println(element)
We could implement 'CollectionType' and 'MutableCollectionType' (the latter only for 'NSMutableOrderedSet' ) to make the 'NS(Mutable)OrderedSet' behave like collections of the Swift standard library.
Not sure if the code above follows best practices as I'm still trying to circle around all of these protocols.
Ivica M.
source share