数组和集合 / 迭代器

//custom enumerator: nil ends the
//iteration; NSEnumerator supports
//for-in out of the box
@interface Counter : NSEnumerator
- (instancetype)initWithLow:(int)low
    high:(int)high step:(int)step;
@end

@implementation Counter {
    int _current, _high, _step;
}

- (instancetype)initWithLow:(int)low
    high:(int)high step:(int)step {
    self = [super init];
    if (self) {
        _current = low;
        _high = high;
        _step = step;
    }
    return self;
}

- (id)nextObject {
    if (_current > _high) {
        return nil;
    }
    int result = _current;
    _current += _step;
    return @(result);
}
@end

Counter *counter = [[Counter alloc]
    initWithLow:3 high:9 step:2];
for (NSNumber *n in counter) {
    //3, 5, 7, 9
}