Generate a sequence of values in Swift

Generate a sequence of values in Swift

Recently I had to generate an array of numbers that started and ended on specific values. I thought I would have to use a for loop to iterate from first value to last one and manually append values to an array:

var array: [Int] = []

for i in 0..<5 {
	array.append(i)
}

print(array) // [0, 1, 2, 3, 4]

This approach was fine, but Apple already implemented a functions that can swiftly generate sequences:

let strideSequence = stride(from: 0, to: 5, by: 1) 
let array = Array(strideSequence)
print(array) // [0, 1, 2, 3, 4]

The stride(from: to: by:) function returns a sequence from a starting value, but not including an end value, stepping by the specified amount.

There is also a second version of this function stride(from: through: by:) that includes the end value in the returned sequence:

let strideSequence = stride(from: 0, through: 5, by: 1)
let array = Array(strideSequence)
print(array) // [0, 1, 2, 3, 4, 5]

Comments

Anything interesting to share? Write a comment.