Swift generic Function (n choose k) <p>I'm trying to make this JavaScript code in Swift: <a href="https://gist.github.com/axelpale/3118596" rel="nofollow">k_combinations</a></p> <p>And so far i have this in Swift:</p> <pre><code>import Foundation import Cocoa extension Array { func slice(args: Int...) -&gt; Array { var s = args[0] var e = self.count - 1 if args.count &gt; 1 { e = args[1] } if e &lt; 0 { e += self.count } if s &lt; 0 { s += self.count } let count = (s &lt; e ? e-s : s-e)+1 let inc = s &lt; e ? 1 : -1 var ret = Array() var idx = s for var i=0;i&lt;count;i++ { ret.append(self[idx]) idx += inc } return ret } } func kombinaatiot&lt;T&gt;(setti: Array&lt;T&gt;, k: Int) -&gt; Array&lt;Array&lt;T&gt;&gt; { var i: Int, j: Int if (k &gt; setti.count || k &lt;= 0) { return [] } if (k == setti.count) { return [setti] } if (k == 1) { var combs: Array&lt;T&gt; = [] for var i = 0; i &lt; setti.count; i++ { combs += [setti[i]] } return [combs] } var combs: Array&lt;Array&lt;T&gt;&gt; = [[]] for var i = 0; i &lt; setti.count - k + 1; i++ { var head = setti.slice(i,i + 1) var tailcombs = kombinaatiot(setti.slice(i + 1), k - 1) for var j = 0; j &lt; tailcombs.count; j++ { combs += ([head + tailcombs[j]]) } } println(combs) return combs } </code></pre> <p>But problem is that my function prints</p> <pre><code>[[], [1, 2, 2, 3, 4], [2, 3, 3, 4], [3, 4, 4]] </code></pre> <p>when it should print </p> <pre><code>[[1,2], [1,3], [2, 3] </code></pre> <p>What i'm doing wrong here? Im noobie at coding, and my javascript skills aren't very well, but that javascript worked for me, but in swift i can't make that work.</p>