Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, what is a 'progression'?

According to the Control Flow section in the Swift Language Guide,

The for-in loop performs a set of statements for each item in a range, sequence, collection, or progression.

I'm pretty sure I know what three of these are:

  1. range: something defined with the range operators, ... or ..<
  2. sequence: something that conforms to the SequenceType protocol (documentation not anywhere obvious, but various people have reverse-engineered it)
  3. collection: either of the Swift collection types, i.e. Array and Dictionary

(I note #3 is probably redundant as Array and Dictionary both seem to conform to SequenceType.)

But what's a "progression"? Is it some fourth thing, or was the writer just being wordy?


ETA: I see there's a CollectionType protocol as well, so that explains #3.

like image 966
David Moles Avatar asked Feb 25 '15 05:02

David Moles


2 Answers

The first mention I see of "progression" besides the for-in documentation is in the comments of the swift framework where the stride methods are defined.

func stride<T : Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T>

Return the sequence of values (start, start + stride, start + stride + stride, ... last) where last is the last value in the progression that is less than end.

func stride<T : Strideable>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T>

Return the sequence of values (start, start + stride, start + stride + stride, ... last) where last is the last value in the progression less than or equal to end. Note:: There is no guarantee that end is an element of the sequence.

So in short, "progression" refers to the Strideable protocol similar to how "collection" refers to the CollectionType protocol and the classes and structs that conform to it.

Numeric types (Int, Double, Float, UnsafePointer, Bit, etc...) tend to conform to this protocol so they may be incremented/decremented for for in loops. Full inheritance graph for the Strideable protocol found here.

like image 115
Ian Avatar answered Sep 22 '22 09:09

Ian


What you are probably looking for is this kind of loop ( for in stride )

for i in stride(from: 1, to: 10, by: 2) {
    println(i)
}

that is the new syntax replacement for

for var i = 1; i < 10; i += 2 {
    println(i)
}
like image 28
Leo Dabus Avatar answered Sep 26 '22 09:09

Leo Dabus