I am trying to build a 3D array. Here is a code that i modified from a 2D array. The 3D array does not print my arrays out, from the values that i defined it to be. There is something wrong with my getter and setter inside my subscripts. Can someone advise me?
import UIKit
class Array3D {
var zs:Int, ys:Int, xs:Int
var matrix: [Int]
init(zs: Int, ys:Int, xs:Int) {
self.zs = zs
self.ys = ys
self.xs = xs
matrix = Array(count:zs*ys*xs, repeatedValue:0)
}
subscript(z:Int, ys:Int, xs:Int) -> Int {
get {
return matrix[ zs * ys * xs + ys ]
}
set {
matrix[ zs* ys * xs + ys ] = newValue
}
}
func zsCount() -> Int {
return self.zs
}
func colCount() -> Int {
return self.ys
}
func rowCount() -> Int {
return self.xs
}
}
var dungeon = Array3D(zs: 5, ys: 5, xs: 5)
dungeon[1,0,0] = 1
dungeon[0,4,0] = 2
dungeon[0,0,4] = 3
dungeon[0,4,4] = 4
print("You created a dungeon with \(dungeon.zsCount()) z value \(dungeon.colCount()) columns and \(dungeon.rowCount()) rows. Here is the dungeon visually:\n\n")
for z in 0..<5 {
for y in 0..<5 {
for x in 0..<5 {
print(String(dungeon[z,x,y]))
}
print("\n")
}
print("\n")
}