title: How can I extend typed Arrays in Swift?
body: <p>How can I extend Swift's <code>Array&lt;T&gt;</code> or <code>T[]</code> type with custom functional utils? </p>
  
  <p>Browsing around Swift's API docs shows that Array methods are an extension of the <code>T[]</code>, e.g:</p>
  
  <pre><code>extension T[] : ArrayType {
      //...
      init()
  
      var count: Int { get }
  
      var capacity: Int { get }
  
      var isEmpty: Bool { get }
  
      func copy() -&gt; T[]
  }
  </code></pre>
  
  <p>When copying and pasting the same source and trying any variations like:</p>
  
  <pre><code>extension T[] : ArrayType {
      func foo(){}
  }
  
  extension T[] {
      func foo(){}
  }
  </code></pre>
  
  <p>It fails to build with the error:</p>
  
  <blockquote>
    <p>Nominal type <code>T[]</code> can't be extended</p>
  </blockquote>
  
  <p>Using the full type definition fails with <code>Use of undefined type 'T'</code>, i.e:</p>
  
  <pre><code>extension Array&lt;T&gt; {
      func foo(){}
  }
  </code></pre>
  
  <p>And it also fails with <code>Array&lt;T : Any&gt;</code> and <code>Array&lt;String&gt;</code>.</p>
  
  <p>Curiously Swift lets me extend an untyped array with:</p>
  
  <pre><code>extension Array {
      func each(fn: (Any) -&gt; ()) {
          for i in self {
              fn(i)
          }
      }
  }
  </code></pre>
  
  <p>Which it lets me call with:</p>
  
  <pre><code>[1,2,3].each(println)
  </code></pre>
  
  <p>But I can't create a proper generic type extension as the type seems to be lost when it flows through the method, e.g trying to <a href="https://stackoverflow.com/q/24025633/85785">replace Swift's built-in filter with</a>:</p>
  
  <pre><code>extension Array {
      func find&lt;T&gt;(fn: (T) -&gt; Bool) -&gt; T[] {
          var to = T[]()
          for x in self {
              let t = x as T
              if fn(t) {
                  to += t
              }
          }
          return to
      }
  }
  </code></pre>
  
  <p>But the compiler treats it as untyped where it still allows calling the extension with: </p>
  
  <pre><code>["A","B","C"].find { $0 &gt; "A" }
  </code></pre>
  
  <p>And when stepped-thru with a debugger indicates the type is <code>Swift.String</code> but it's a build error to try access it like a String without casting it to <code>String</code> first, i.e:</p>
  
  <pre><code>["A","B","C"].find { ($0 as String).compare("A") &gt; 0 }
  </code></pre>
  
  <p>Does anyone know what's the proper way to create a typed extension method that acts like the built-in extensions?</p>