How to check whether a matrix is a square matrix in Swift

1 Answer

0 votes
import Foundation

func isSquareMatrix<T>(_ matrix: [[T]]) -> Bool {
    let size = matrix.count
    
    return matrix.allSatisfy { $0.count == size }
}

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

if isSquareMatrix(matrix) {
    print("The matrix is a square matrix.")
} else {
    print("The matrix is not a square matrix.")
}




/*
run:

The matrix is a square matrix.

*/

 



answered Oct 7, 2025 by avibootz
...