Nested arrays using Any/AnyObject
<p>According to Apple's official book "The Swift Programming Language (Swift 2.1)":</p>

<blockquote>
  <ul>
  <li>AnyObject can represent an instance of any class type.</li>
  <li>Any can represent an instance of any type at all, including function types.</li>
  </ul>
</blockquote>

<p>Knowing that, I wanted to emulate Python-like nested list using an <code>Any</code> array.</p>

<pre><code>let array = [1, 2, [3, 4], [5, 6, [7, 8]], 1]
</code></pre>

<p>Since <code>Int</code> and <code>Array</code> are value types, I supposed that <code>array</code> would be typed as <code>[Any]</code></p>

<p>But this wasn't the case here : </p>

<pre><code>func flatten(list:[Any]) -&gt; [Any] {
    var new = [Any]()
    for element in list {
        if let array = element as? [Any] {
            // this code never runs
            let flattened = flatten(array)
            for x in flattened {
                new.append(y)
            }
        }else{
            new.append(element)
        }
    }
    return new
}
</code></pre>

<p><em>Note:</em> calling this function gave me <code>EXC_BAD_INSTRUCTION</code> error at first until I did this tweak : </p>

<pre><code>let array : [Any] = [1, 2, [3, 4], [5, 6, [7, 8]], 1]

Output :   [1, 2, [3, 4], [5, 6, [7, 8]], 1]
Expected : [1, 2, 3, 4, 5, 6, 7, 8, 1]
</code></pre>

<h2>Unexplained Solution:</h2>

<p>I replaced everywhere in this example <code>Any</code> by <code>AnyObject</code> </p>

<p>Numbers now are of type <code>NSNumber</code></p>

<pre><code>func flatten(list:[AnyObject]) -&gt; [AnyObject] {
    var new = [AnyObject]()
    for element in list {
        if let array = element as? [AnyObject] {
            let flattened = flatten(array)
            for x in flattened {
                new.append(y)
            }
        }else{
            new.append(element)
        }
    }
    return new
}

Output :   [1, 2, 3, 4, 5, 6, 7, 8, 1]
Expected : [1, 2, 3, 4, 5, 6, 7, 8, 1]
</code></pre>

<h2>Question :</h2>

<p>Why is it working with <code>[AnyObject]</code> / <code>NSArray</code> and not with <code>[Any]</code>, despite the fact that integer literals are mainly of type <code>Int</code> not <code>NSNumber</code> and array literals are of type <code>Array</code> and not <code>NSArray</code>? <em>Is something wrong with my example?</em>  </p>