目标 C 相当于 PHP 范围函数? [英] Objective C equivalent of PHP range function?
问题描述
我想快速创建一个从 0 到 10000 的数字数组,但步进增量为 500,对于如下所示的数组:
I want to quickly create an array of numbers from 0 to 10000 but with stepping increments of 500, for an array that looks like this:
@[@0, @500, @1000, ... @10000]
在 PHP
中,它内置于 range 函数,你可以像这样生成它:range(0, 10000, 500)
in PHP
, this is built in to the range function, you could generate it like this: range(0, 10000, 500)
我并不是真的在寻找答案,比如循环遍历一些初始数组或数字超过 0-10000 并使用模数或其他东西,我只是想知道是否有内置函数或常用速记来执行此操作
I'm not really looking for answers like looping over some initial array or numerically over 0-10000 and using modulus or something, I just want to know if there's a built in function or common shorthand for doing this
推荐答案
Objective-C 中没有类似的内置函数.正如您所暗示的,最好的方法是循环如下:
There is no built-in function like that in Objective-C. As you hinted, the best way to do it is by looping as follows:
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i <= 10000; i += 500) {
[array addObject:@(i)];
}
如果您想创建一个与 PHP 范围函数类似的方法:返回从 start 到 end 的元素数组,包括.
If you want to make a method that works similarly to the PHP range function: Returns an array of elements from start to end, inclusive.
这样做:
+ (NSArray *)rangeWithStart:(NSInteger)start end:(NSInteger)end step:(NSInteger)step {
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSInteger i = start; i <= end; i += step) {
[array addObject:@(i)];
}
return [array copy];
}
这篇关于目标 C 相当于 PHP 范围函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!