
Swift Sequences and Lazy Evaluation - ianstallings
http://www.scottlogic.com/blog/2014/06/26/swift-sequences.html
======
masklinn
[http://robots.thoughtbot.com/swift-
sequences](http://robots.thoughtbot.com/swift-sequences) has a somewhat more
advanced and in-depth overview of Sequence and Generator, although it doesn't
use the laziness possibilities. It also points to the "Advanced Swift" WWDC
session which covers the subject.

------
fleitz
There's a different syntax available for sequences utilizing trailing closure
syntax, in my opinion it's much more succinct, 13 lines vs. 22

    
    
      let Fibbonacci = SequenceOf { 
    
        var current = -1, last = 0
    
        return GeneratorOf {
          if current == -1 {
            current = 0
          } else if current == 0 {
            current = 1
          } else {
            var next = last + current
            last = current
            current = next
          }
          return current
        }
      }

~~~
ghusbands
And they'd both be five lines shorter if the fibonacci implementation weren't
overcomplicated, making your gain even more significant (8 lines vs 17).

    
    
      let Fibbonacci = SequenceOf {
     
        var current = 0, next = 1
        
        return GeneratorOf {
          var ret = current
          current = next
          next = next + ret
          return ret
        }
      }

~~~
remon
It's interesting how that sort of thing actually hurts the article. When I
skimmed through that code I got stuck on "Why is this Fibonacci implementation
so verbose?" rather than the actual topic of the paragraph in question.

------
jheriko
this stuff is always interesting. i don't understand how it ends up in the
language in the form of 'for-in' though.

the syntax is similar to the old school BASIC for loop, but the implementation
is heavier in the vast majority of cases where you write simple code for the
loop body (i.e. avoiding heavyweight language constructs). Of course unless
the compiler optimised out the lazy evaluations...

i would like laziness in this situation to be described by a keyword please,
so that i don't have a whole language feature being slower by premature
optimisation I don't get a say in... :)

~~~
ColinE
I think you misunderstand, the Swift for-in relies on a sequence, i.e. an
object that 'feeds' it a certain number of items. However, the sequence does
not have to be lazy in its evaluation. And there is nothing that couples for-
in to the concept of lazy evaluation.

When you use for-in to iterate over arrays, strings, dictionaries etc ... it
is an iteration of the type you are no doubt familiar with, where you are
iterating over some fixed pre-computed structure.

However, sequences can also generate their 'next' value lazily.

It is something that I consider to be an interesting topic, but would
certainly not advocate that everything should become a lazy operation.

