【问题标题】:Error while using subscript: Cannot subscript a value of type... with an index of type使用下标时出错:无法使用类型索引为类型值下标...
【发布时间】: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


    【解决方案1】:

    您的subscript(position:Position) -> Cellule 方法是一种方法 struct Grille,因此您只能将其应用于 该类型(而不是具有[Cellule] 类型的laGrille)。

    你的意思可能是

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

    然后下标方法访问(私有)laGrille 属性。

    【讨论】:

    • 怎么样,谢谢,你是对的!非常感谢你!然后我必须将包含Cellule 的数组封装在一个新类型上,并在其上移动subscript 以获得:laGrille[thePosition].someValue = active
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2020-02-08
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多