【发布时间】:2015-05-19 16:48:22
【问题描述】:
我想在自定义类型Cellule 的一维数组上使用subscript。
这个数组表示一个二维的,并使用一个名为Position的自定义类型来封装。
以下代码无法编译,指定行出现以下错误:
- 找不到成员“someValue”
- 无法使用“Position”类型的索引为“[Cellule]”类型的值下标
您可能注意到Celluletype 在数组中不是可选的。
这里是代码:
///
/// ◀──────row──────▶
///
/// ▲ ╔═══════════════╗
/// │ ║ ┌─┐ ║
/// │ ║ │█│──╬─────▶ Cellule
/// column ║ └─┘ ║
/// │ ║ ║
/// │ ║ ║
/// │ ║ ║
/// ▼ ╚═════ Grille ══╝ ┌ Position ───┐
/// │ │
/// │• row │
/// │• column │
/// └─────────────┘
/// Encapsulate position information
struct Position {
var row: Int
var column: Int
}
/// Data stored in the array
struct Cellule {
var someValue:Bool
/// some other values
}
/// Array to store data
struct Grille {
let width:Int // Number of columns
let height:Int // Number of lines
private var laGrille:[Cellule]
mutating func changeSomething (thePosition: Position, value:Bool) {
laGrille[thePosition].someValue = active
/// Error: Could not find member 'someValue'
let cell:Cellule = laGrille[thePosition]
/// Error: Cannot subscript a value of type '[Cellule]' with an index of type 'Position'
}
subscript(position:Position) -> Cellule {
get {
return laGrille[position.row*width + position.column]
}
set {
laGrille[position.row*width + position.column] = newValue
}
}
}
【问题讨论】:
标签: swift