设置:
我的应用程序有一个通用函数,可以对其中心的任意元素的二次矩阵进行点镜像:
func pointMirroredMatrix<T>(_ matrix: inout [[T]]) {
assert(matrix.count > 0 && matrix[0].count > 0) // Ensure matrix is not empty
assert(matrix.count == matrix[0].count) // Ensure matrix is quadratic
let n = matrix.count // The matrix is n x n
for row in 0 ..< n/2 {
for col in 0 ..< n {
// Swapping elements
(matrix[row][col], matrix[n - 1 - row][n - 1 - col]) = (matrix[n - 1 - row][n - 1 - col], matrix[row][col])
}
}
}
我想编写一个 Swift 测试来检查它是否func pointMirroredMatrix
正常工作。
因此我首先定义:
typealias PointMirroredMatrixParams = (matrix: [[Any]], expectedResult: [[Any]])
let pointMirroredMatrixArgs: [PointMirroredMatrixParams] = [(matrix: [[0, 1], [0, 0]],
expectedResult: [[0, 0], [1, 0]])]
struct VisionTests {
@Test("pointMirroredMatrix", arguments: pointMirroredMatrixArgs)
func pointMirroredMatrix(p: PointMirroredMatrixParams) throws {
// see below
}
请注意,矩阵元素的类型为Any
,因为@Test
不允许使用泛型。
测试应执行以下操作:
var mirroredMatrix = deepCopyMatrix(p.matrix) // Make deep copy
vision.pointMirroredMatrix(&mirroredMatrix) // Mirror the copy
let mirroredCorrectly = maticesAreEqual(p.expectedResult, mirroredMatrix)
#expect(mirroredCorrectly)
问题:
我无法写入func maticesAreEqual
,因为测试参数传递的矩阵是类型Any
。我尝试了以下操作,但没有成功:
func maticesAreEqual(_ matrix1: [[Any]], _ matrix2: [[Any]]) -> Bool {
guard matrix1.count == matrix2.count else { return false }
guard matrix1[0].count == matrix2[0].count else { return false }
guard !matrix1.isEmpty else { return true }
guard type(of: matrix1[0][0]) == type(of: matrix2[0][0]) else { return false }
guard type(of: matrix1[0][0]) == (any Equatable).self else { return false }
// Here it is known that both matrices have the same dimension, their elements are of the same type and are equatable
// But how to find out if they are equal?
for i in 0 ..< matrix1.count {
for j in 0 ..< matrix1[i].count {
if matrix1[i][j] != matrix2[i][j] { return false } // Build error
}
}
return true
}
但由于类型原因,内循环中的指令无法编译Any
。我收到错误Type 'Any' cannot conform to 'Collection'
。
我的问题:
如何func pointMirroredMatrix
使用传入的具有不同类型元素的矩阵进行测试@Test
?