Continuous numbers in an Objective-C array, such as range () in Python

Python can create a list with contiguous numbers, such as:

numbers=range(1,10); // >> [1,2,3,4,5,6,7,8,9] 

How to implement this in Objective-c?

+6
source share
4 answers

Reading your statement "You just need an array with continuous numbers, I don't want to initialize it with a loop." Let me ask: what is more important for you: to have an array or "something" representing a continuous range (natural). Take a look at NSIndexSet It may come close to what you want. You initialize it with

 [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1,9)]; 

Iterating over this set is as simple as iterating over an array and does not need NSNumbers.

+10
source

Objective-C (or Foundation actually) does not have a special function for this. You can use:

 NSMutableArray *array = [NSMutableArray array]; for(int i=1; i<10; i++) { [array addObject:@(i)]; // @() is the modern objective-c syntax, to box the value into an NSNumber. } // If you need an immutable array, add NSArray *immutableArray = [array copy]; 

If you want to use it more often, you can put it in a category.

+5
source

You can use NSRange .

 NSRange numbers = NSMakeRange(1, 10); 

NSRange is just a structure and not like a Python range object.

 typedef struct _NSRange { NSUInteger location; NSUInteger length; } NSRange; 

So you should use access to your members for the loop.

 NSUInteger num; for(num = 1; num <= maxValue; num++ ){ // Do Something here } 
+4
source

You can subclass an NSArray with a class for ranges. Subclassing NSArray is pretty simple:

  • you need a suitable initialization method that calls [super init] ; and

  • you need to override count and objectAtIndex:

You can do more, but you do not need. There is no verification code in this sketch:

 @interface RangeArray : NSArray - (id) initWithRangeFrom:(NSInteger)firstValue to:(NSInteger)lastValue; @end @implementation RangeArray { NSInteger start, count; } - (id) initWithRangeFrom:(NSInteger)firstValue to:(NSInteger)lastValue { // should check firstValue < lastValue and take appropriate action if not if((self = [super init])) { start = firstValue; count = lastValue - firstValue + 1; } return self; } // to subclass NSArray only need to override count & objectAtIndex: - (NSUInteger) count { return count; } - (id)objectAtIndex:(NSUInteger)index { if (index >= count) @throw [NSException exceptionWithName:NSRangeException reason:@"Index out of bounds" userInfo:nil]; else return [NSNumber numberWithInteger:(start + index)]; } @end 

You can use it as follows:

 NSArray *myRange = [[RangeArray alloc] initWithRangeFrom:1 to:10]; 

If you copy a RangeArray , it will become a normal array of NSNumber objects, but you can avoid it if you want using the NSCopying protocol NSCopying .

+1
source

Source: https://habr.com/ru/post/922023/


All Articles