【发布时间】:2015-01-21 18:07:14
【问题描述】:
我正在尝试构建一个 3D 数组。这是我从二维数组修改的代码。 3D 数组不会从我定义的值中打印出我的数组。我的下标中的 getter 和 setter 有问题。有人可以给我建议吗?
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")
}
【问题讨论】: