This is not the cons
operator, per se, but you can use the +
operator for arrays to append or prepend an array onto a mutable or immutable array in "constructor style"; constructing a new array with the concatenated result.
From the Swift Language Guide - Collection Types:
Creating an Array by Adding Two Arrays Together
You can create a new array by adding together two existing arrays with
compatible types with the addition operator (+
). The new array’s
type is inferred from the type of the two arrays you add together:
...
I.e.,
let foo = [1, 2]
let bar = foo + [3] // [1, 2, 3], "cons(foo, 3)"
let baz = [-1, 0] + bar // [-1, 0, 1, 2, 3], "cons([-1, 0], bar)"
Note, however, that this does not run in amortised constant time, since we require allocating new memory and copying the result into this. However, since arrays are value types in Swift, I don't see how how any operation on immutable arrays---such that we create a new immutable array---will run in constant time, since we will always require copying for this (even if, sometimes, this might be performed lazily).
Hence, the performance of the above shouldn't differ from constructing a new array using .append
/.appendContentsOf
on an existing mutable one followed by copying; the former step running in amortised constant time (due to exponentially growing pre-allocation of array space), but the latter one running in linear time.