This question already has an answer here:
这个问题已经有了答案:
- Is there a way to instantly generate an array filled with a range of values in Swift? 3 answers
- 是否有一种方法可以在Swift中立即生成一个包含一系列值的数组?3答案
I know that I can create an array with repeated values in Swift with:
我知道我可以用Swift创建一个具有重复值的数组:
var myArray = [Int](count: 5, repeatedValue: 0)
But is there a way to create an array with incremented values such as [0, 1, 2, 3, 4]
other than to do a loop such as
但是有没有一种方法可以创建一个带有递增值的数组,比如[0,1,2,3,4],而不是执行一个循环
var myArray = [Int]()
for i in 0 ... 4 {
myArray.append(i)
}
I know that code is pretty straightforward, readable, and bulletproof, but it feels like I should be able pass some function in some way to the array as it's created to provided the incremented values. It might not be worth the cost in readability or computationally more efficient, but I'm curious nonetheless.
我知道代码非常简单、易读和防弹,但是感觉我应该能够以某种方式将一些函数传递给数组,因为它被创建时提供了递增的值。它可能不值得在可读性或计算上更有效率,但我仍然很好奇。
1 个解决方案
#1
75
Use the ...
notation
使用……符号
let arr1 = 0...4
That gets you a Range
, which you can easily turn into a "regular" Array
:
这就得到了一个范围,您可以很容易地将其转换为“常规”数组:
let arr2 = Array(0...4)
#1
75
Use the ...
notation
使用……符号
let arr1 = 0...4
That gets you a Range
, which you can easily turn into a "regular" Array
:
这就得到了一个范围,您可以很容易地将其转换为“常规”数组:
let arr2 = Array(0...4)