title: How to implement CollectionOf in Swift
body: <p>Looking at <a href="https://stackoverflow.com/questions/26832498/how-is-a-type-erased-generic-wrapper-implemented">this question</a>, I'm trying to implement an equivalent for <code>CollectionType</code> called <code>CollectionOf</code>, but I'm having trouble with one of the constraints:</p>
  
  <pre><code>struct CollectionOf&lt;T, Index: ForwardIndexType&gt;: CollectionType {
      init&lt;C: CollectionType where C.Generator.Element == T, C.Index == Index&gt;(_ collection: C) {
          // etc.
      }
      // etc.
  }
  </code></pre>
  
  <p>This does not compile. Let's ignore the fact that I haven't implemented the members of <code>CollectionType</code> yet. I'll get to that. The problem I face is that the compiler doesn't like my <code>init</code>. It complains, "Same-type constraint Index does not conform to required protocol ForwardIndexType." Clearly it does.</p>
  
  <p>Perhaps we have a compiler bug. Perhaps my syntax is wrong. Whatever the case, how can I implement <code>CollectionOf</code>?</p>
  
  <h1>EDIT</h1>
  
  <p>Here is a working implementation. Due to the problem noted above, it suffers from the serious flaw that the <code>Index typealias</code> of <code>CollectionType</code> is not constrained to be same as that of the wrapped <code>CollectionType</code>. This means I am forced to cast, which could in theory cause a problem at runtime rather than at compilation time, which defeats the purpose of static typing.</p>
  
  <pre><code>struct CollectionOf&lt;T, I: ForwardIndexType&gt;: CollectionType {
      private let _generate: () -&gt; GeneratorOf&lt;T&gt;
      private let _startIndex: () -&gt; I
      private let _endIndex: () -&gt; I
      private let _subscript: (I) -&gt; T
  
      init&lt;C: CollectionType where C.Generator.Element == T&gt;(_ collection: C) {
          _generate = { GeneratorOf(collection.generate()) }
          _startIndex = { collection.startIndex as I }
          _endIndex = { collection.endIndex as I }
          _subscript = { i in collection[i as C.Index] }
      }
  
      var startIndex: I {
          return _startIndex()
      }
  
      var endIndex: I {
          return _endIndex()
      }
  
      func generate() -&gt; GeneratorOf&lt;T&gt; {
          return _generate()
      }
  
      subscript (i: I) -&gt; T {
          return _subscript(i)
      }
  }
  </code></pre>