Iterating over an NSOrderedSet

纵饮孤独 提交于 2019-12-03 22:41:09

You can iterate over an ordered set with

let orderedSet = NSOrderedSet(array: [ 42, 43, 44])
orderedSet.enumerateObjectsUsingBlock { (elem, idx, stop) -> Void in
    println("\(idx): \(elem)")
}

UPDATE: As of Swift 1.2 (Xcode 6.3), NSOrderedSet conforms to SequenceType and can be enumerated with for ... in ...:

let orderedSet = NSOrderedSet(array: [ 42, 43, 44])
for elem in orderedSet {
    println(elem)
}

NSOrderedSet doesn't conform to SequenceType. NSOrderedSet is subclass of NSObject and not NSSet as one could imagine. I guess Apple engineers overlooked it.

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.

import Swift
import Foundation


println("Simplest, most accessible, O(1) performance: shallow copy to array:")

var set = NSOrderedSet(array: map(0...7) { d in d })
for d in set.array as [Int] {
    print("\t\(d)")
}

println("\n\nIn general - for other types and cases, you could create a sequence:")

extension NSOrderedSet {
    func sequenceOf<T>(t:T.Type) -> SequenceOf<T> {
        var current = 0
        return SequenceOf(GeneratorOf({ () -> T? in
            return current < self.count ? self.objectAtIndex(current++) as? T : nil
        }))
    }
}

for d in set.sequenceOf(Int.self) {
    print("\t\(d)")
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!