在一个区间上创建整数列表

[英]Create list of integers on an interval


I want to create a list of integers on an interval increasing with a certain step, for example [0,1,2,3,4,5,6,7,8,9,10]. How could I do this without creating a separate method?

我想要创建一个以特定步骤递增的区间上的整数列表,例如[0,1,2,3,4,5,6,7,8,9,10]。如果不创建单独的方法,我怎么能做到这一点呢?

1 个解决方案

#1


4  

Swift 2

斯威夫特2

To create an array of Ints in sequence you can use a "range":

要按顺序创建Ints数组,可以使用“range”:

let a = Array(0...10)  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Here 0...10 makes the Range and the Array initializer makes the Range into an Array of Ints.

这里0…10使范围和数组初始化器使范围成为一个Ints数组。

There's also this variant:

还有这个变体:

let a = Array(0..<10)  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

And to do the same thing but with a different stepping, you can use "stride":

要做同样的事情,但是用不同的步伐,你可以使用"stride":

let b = Array(0.stride(through: 10, by: 2))  // [0, 2, 4, 6, 8, 10]

Here stride starts on 0 and goes through 10 by steps of 2.

这里大步从0开始,走10步,走2步。

It also has a variant:

它还有一个变体:

let b = Array(0.stride(to: 10, by: 2))  // [0, 2, 4, 6, 8]

Swift 3

斯威夫特3

The syntax for stride has changed, now it's a free function.

stride的语法已经改变,现在它是一个自由函数。

let b = Array(stride(from: 0, through: 10, by: 2))  // [0, 2, 4, 6, 8, 10]
let b = Array(stride(from: 0, to: 10, by: 2))  // [0, 2, 4, 6, 8]
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2016/01/28/3361ff2fbff0a65943ea2a27c2f824e6.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告