CO fans: before you jump into conclusion it is a duplicate, there are 2 distinct flavours of arrays, and it seems I am asking about less popular one.
So far, I
An example implementation supporting arbitrary number of dimensions:
struct ArrayMultiDimension {
private var _base:[T]
let _dimensions: [Int]
init(initialValue: T, dimensions:Int...) {
_base = Array(count: reduce(dimensions, 1, *), repeatedValue: initialValue)
_dimensions = dimensions
}
private func _position2idx(position:[Int]) -> Int {
assert(position.count == _dimensions.count)
return reduce(Zip2(_dimensions, position), 0) {
assert($1.0 > $1.1)
return $0 * $1.0 + $1.1
}
}
subscript(position:Int...) -> T {
get { return _base[_position2idx(position)] }
set { _base[_position2idx(position)] = newValue }
}
}
// Usage:
var array3d = ArrayMultiDimension(initialValue: "", dimensions: 4,3,2)
for x in 0 ..< 4 {
for y in 0 ..< 3 {
for z in 0 ..< 2 {
array3d[x,y,z] = "\(x)-\(y)-\(z)"
}
}
}
array3d[1,2,0] = "foo"
But, this could be very slow...