title: Equivalent for loop complex condition
body: <p>I have code currently in my iOS project that looks like this:</p>
  
  <pre><code>for var i = 0; CGFloat(i) * gridSpacing.width * scale &lt; bounds.width; ++i
  </code></pre>
  
  <p>I am now receiving warnings that this style for loop will be deprecated. Everywhere I look on Stack Overflow and elsewhere suggests using stride for complex for loops. However, stride doesn't help me here, as the end condition is not a simple comparison to another integer.</p>
  
  <p>How do I do this in swift with a for-in loop?</p>
  
  <p>Note, I could loop a CGFloat, but I want to avoid the incremental error by repeatedly adding floats.</p>
  
  <p>I could also use a while loop, but I have several of these loops in the same function, and for creates a nice new scope for i. Swift doesn't seem to like arbitrary new scopes.</p>
  
  <p>Edit: based on @Sulthan's answer, I created a SequenceType to do this. IMO, something like this should be in swift if for loops are being removed:</p>
  
  <pre><code>struct forgenerator : GeneratorType
  {
      typealias Element = Int
      typealias Condition = (Element) -&gt; Bool
      var idx : Element
      var condition : Condition
      var increment: Element
  
      mutating func next() -&gt; Element? {
          if condition(idx)
          {
              let result = idx
              idx += increment
              return result
          }
  
          return nil
      }
  }
  
  struct forsequence : SequenceType
  {
      typealias Generator = forgenerator
      var startPoint : Generator.Element
      var condition : Generator.Condition
      var increment : Generator.Element
  
      func generate() -&gt; Generator {
          return forgenerator(idx: startPoint, condition: condition, increment: increment)
      }
  }
  
  
  func forgen(start: Int, condition: (Int) -&gt; Bool, increment: Int) -&gt; forsequence
  {
      return forsequence(startPoint: start, condition: condition, increment: increment)
  }
  
  func forgen(start: Int, condition: (Int) -&gt; Bool) -&gt; forsequence
  {
      return forgen(start, condition: condition, increment: 1)
  }
  </code></pre>
  
  <p>Usage:</p>
  
  <pre><code>for i in forgen(0, condition: { CGFloat($0) * self.gridSpacing.width * self.scale &lt; self.bounds.width})
  </code></pre>
  
  <p>Note, had to use self here everywhere because all those vars were members of a class.</p>