Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Overload the '*' Multiplication Operator for Custom Swift Types
Written by Team Kodeco

When working with custom types in Swift, you may want to overload the * operator.

For example, if you have a class for a matrix, you might want to implement matrix multiplication. Here’s an example:

class Matrix {
  var matrix: [[Int]]
  init(matrix: [[Int]]) {
    self.matrix = matrix
  }
}

extension Matrix {
  static func *(lhs: Matrix, rhs: Matrix) -> Matrix {
    let rows = lhs.matrix.count
    let columns = rhs.matrix[0].count
    let rowColumn = rhs.matrix.count
    var result = [[Int]](repeating: [Int](repeating: 0, count: columns), count: rows)
    for i in 0..<rows {
      for j in 0..<columns {
        for k in 0..<rowColumn {
          result[i][j] += lhs.matrix[i][k] * rhs.matrix[k][j]
        }
      }
    }
    return Matrix(matrix: result)
  }
}

In this example, you define a Matrix class with a matrix property containing a 2D array of integers. You then define an extension on the Matrix class and overload the * operator by defining a static function called * that takes two Matrix parameters and returns a new Matrix instance that is the result of matrix multiplication.

Now you can use the * operator to multiply two Matrix instances:

let matrix1 = Matrix(matrix: [[1,2],[3,4]])
let matrix2 = Matrix(matrix: [[2,0],[1,2]])
let matrix3 = matrix1 * matrix2
print(matrix3.matrix) // [[4,4],[10,8]]

It’s important to note that, for matrix multiplication the number of columns of first matrix should be equal to the number of rows of second matrix, otherwise it’ll throw an error.

© 2024 Kodeco Inc.