I have defined a struct for 2D Arrays :
struct Array2D<T: Equatable> {
var matrix : [[T]]
private var nRows, nCol : Int
// .......
I have defined an extension for ==
extension Array2D : Equatable { }
func ==<T>(x: Array2D<T>, y: Array2D<T>) -> Bool { /
if (x.nRows != y.nRows) || (x.nCol != y.nCol) { return false }
for i in 0..<x.nRows {
for j in 0..<x.nCol {
if (x.matrix[i][j] != y.matrix[i][j]) { return false }
}
}
return true
}
I want now to define a ~operator, that will work only for Bool (T : Bool) ; something like:
prefix func ~<T>(x: Array2D<T>) -> Array2D<T> {
var y = x /
for i in 0..<x.nRows {
for j in 0..<x.nCol {
y.matrix[i][j] = !x.matrix[i][j]
}
}
return y
}
Of course, this should be limited to T : Bool ; how can I insert a "where T == Bool" clause in the operator definition ?
I think you would just do this, which as jeschot mentioned is not generic; there's no reason it would need to be.
prefix func ~(x: Array2D<Bool>) -> Array2D<Bool> {
var y = x
for i in 0..<x.nRows {
for j in 0..<x.nCol {
y.matrix[i][j] = !x.matrix[i][j]
print(i, j)
}
}
return y
}
BTW, you probably need to make sure you have code in your struct to make sure nRows and nCol match the actual size of matrix. You may already be doing this, but since you didn't post your whole structure it's not obvious, so I thought I'd mention it. You could make them read-only computed properties that return the appropriate array's count property.