我正在尝试构建一个3D数组。这里是我从2D数组修改的代码。 3D阵列不会将我的阵列从我定义的值中打印出来。我的下标中有我的getter和setter错误。有人可以提醒我吗?xcode swift 3D arrays
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")
}
@Antonion谢谢!有用! z和zs,y和ys,x和xs有什么区别?你会向我解释为什么是线性坐标z * ys * xs + y * xs + x?我真的很感谢你的帮助! – 2015-01-21 09:14:21
@Cherry_thia更新了答案 - 希望它有帮助 – Antonio 2015-01-21 10:07:32
感谢您的详细解释。我仍然需要一些时间来了解它,我很欣赏它。 – 2015-01-21 12:54:34