我試圖建立一個FUNC允許總結兩個MATRIX如果他們是等於相同的尺寸,但我得到的嘗試錯誤「EXC_BAD_INSTRUCTION」 ..斯威夫特矩陣和
人有一個想法?我完全封鎖在這個時候..
這裏是我的遊樂場:
import UIKit
enum RisedError: ErrorType {
case DimensionNotEquals
case Obvious(String)
}
func ==(lhs: Matrix, rhs: Matrix) -> Bool {
return (lhs.rows) == (rhs.rows) && (lhs.columns) == (rhs.columns)
}
protocol Operation {
mutating func sumWith(matrixB: Matrix) throws -> Matrix
}
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrixA = Matrix(rows: 2, columns: 2)
matrixA[0,0] = 1.0
matrixA[0,1] = 2.0
matrixA[1,0] = 3.0
matrixA[1,1] = 4.0
var matrixB = Matrix(rows: 2, columns: 2)
matrixB[0,0] = 5.0
matrixB[0,1] = 6.0
matrixB[1,0] = 7.0
matrixB[1,1] = 8.0
print(matrixA)
print(matrixB)
extension Matrix: Operation {
mutating func sumWith(matrixB: Matrix) throws -> Matrix {
guard self == matrixB else { throw RisedError.DimensionNotEquals }
for row in 0...self.rows {
for column in 0...self.columns {
self[row, column] = matrixB[row, column] + self[row, column]
}
}
return self
}
}
do {
try matrixA.sumWith(matrixB)
} catch RisedError.DimensionNotEquals {
print("The two matrix's dimensions aren't equals")
} catch {
print("Something very bad happens")
}
以下是錯誤日誌:
你能顯示其餘的錯誤日誌嗎? – Fogmeister
如果只是矩陣*尺寸*是相同的,你真的定義'A == B'爲真嗎? –
如果在Playground中發生意外事件:1)使用編譯的項目,2)使用* debugger *單步執行代碼。在你的2x2矩陣的情況下,問題幾乎會立即顯現! –