Iterating over an NSOrderedSet

后端 未结 3 1592
傲寒
傲寒 2021-02-18 18:40

I\'m trying to iterate over an instance of NSOrderedSet. Something like this:

func myFunc() {
    var orderedSet = NSOrderedSet(array: [ 42, 43, 44])

    for n          


        
3条回答
  •  鱼传尺愫
    2021-02-18 19:11

    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.Type) -> SequenceOf {
            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

提交回复
热议问题