2015-05-19 90 views
0

我想在自定义类型Cellule的一维数组上使用subscript。 该数组表示二维,并使用名为Position的自定义类型进行封装。使用下标时出错:不能下标值类型为...的类型为

下面的代码不与下面的错误汇编关于指定线:

  • 找不到构件“someValue中”
  • 不能与类型的索引,下标类型的值“[CELLULE]”'位置'

正如您可能会注意到Cellule类型在数组中不是可选的。

这里是代码:

///             
///   ◀──────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 
     } 
    } 

} 

回答

1

subscript(position:Position) -> Cellule方法是一种方法的struct Grille ,这样你就可以将它仅适用于 该类型的实例(而不是laGrille具有类型[Cellule]) 。

你大概的意思是

self[thePosition].someValue = active 
// .... 
let cell = self[thePosition] 

其中下标方法然后访问(私)laGrille 财产。

+0

如何,谢谢,你是对的!非常感谢你! 然后,我必须将包含“Cellule”的数组封装在一个新类型上,并移动其上的'subscript'以获得: 'laGrille [thePosition] .someValue = active' – Domsware

相关问题