【问题标题】:swift changing value in a different column in a matrix changes a different one矩阵中不同列中的快速更改值会更改不同的值
【发布时间】:2018-05-29 18:56:33
【问题描述】:

这是对苹果官方文档中提供的下标选项示例的修改。

所以,我创建了一个结构 -

     struct Matrix {
     let rows: Int, columns: Int
      var print: [Double]
      init(rows: Int, columns: Int) {
      self.rows = rows
      self.columns = columns
      print = Array(repeating:0.0, count:rows * columns) 
       }
       subscript(row: Int, column: Int) -> Double {
        get {
        return print[(row * columns) ]
      }
       set {
        print[(row * columns) ] = newValue
       }
     }
   }

然后我创建了实例 -

    var mat = Matrix(rows: 3, columns: 3)

现在,如果我只是设置值 -

     mat[0,0] = 1.0

并打印 -

     print("\(mat[0,0])") //1.0

它打印出 1.0,应该是这样的

但是当我在上面进行更改并按如下方式设置和打印值时 -

      mat[0,0] = 1.0
      mat[0,1] = 2.0

现在如果我打印

     print("\(mat[0,0])") // 2.0

现在,我的问题是,为什么它[0,0] 变成了 2.0,虽然我没有改变它。

【问题讨论】:

  • 你弄错了索引。这是(row * columns) + column。在您的代码中,row 值为 0 的任何位置都将在零索引中进行评估。

标签: swift options subscript


【解决方案1】:

您在索引print 数组时忘记添加column 值:

struct Matrix {
    let rows: Int, columns: Int
    var print: [Double]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        print = Array(repeating:0.0, count:rows * columns)
    }
    subscript(row: Int, column: Int) -> Double {
        get {
            return print[(row * columns) + column]
        }
        set {
            print[(row * columns) + column] = newValue
        }
    }
}

在修复之前,所有案例 mat[0,0]mat[0,1]mat[0,2] 都在访问相同的值:print[0]

示例:

var mat = Matrix(rows: 2, columns: 3)

mat[0,0] = 1.0
mat[0,1] = 2.0
mat[1,0] = 3.0
mat[1,2] = 4.0

print(mat[0,0])
print(mat[0,1])
print(mat[1,0])
print(mat[1,2])
print(mat)

输出:

1.0
2.0
3.0
4.0
Matrix(rows: 2, columns: 3, print: [1.0, 2.0, 0.0, 3.0, 0.0, 4.0])

注意事项:

  • print 不适合您的数组,因为它也是顶级 Swift 函数。我建议使用其他名称,例如 values
  • 您应该验证索引并在它们超出范围时创建fatalError。如果你不这样做,那么上面示例中的print(mat[0,5]) 将打印4.0,即使columns 的值超出了范围。

    将此检查添加到您的getset

    guard (0..<rows).contains(row) else { fatalError("row index out of range") }
    guard (0..<columns).contains(column) else { fatalError("column index out of range") }
    

【讨论】:

  • 我无法理解 - [(row * columns) + column] 。为什么不能是 [(row * columns) + rows]
  • 公式需要为rowcolumn 的每个组合计算一个唯一值。您建议的公式甚至不使用传入的column 值。我们乘以row * columns 的原因是我们需要将每一行偏移该行的长度,即columns。然后我们添加column 值来计算该值在行中的偏移量。
【解决方案2】:

您创建的不是矩阵,它只是一个Array。当您尝试为变量mat 赋值时,您不会将其设置为矩阵中的指向位置,而是将值设置为位置0 并再次设置mat 中的0。结果:mat = [1.0]。接下来设置mat[0,1] = 2.0。结果:mat = [2.0, 2.0].

例如,要创建二维矩阵,请使用:
var matrix = [[Int]]()

现在为这个矩阵赋值:
matrix[0][0] = 1.0
matrix[0][1] = 2.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多