Swift matrix sum

前端 未结 3 1615
小蘑菇
小蘑菇 2021-01-16 08:18

I\'m trying to develop a func which allows to sum two matrix if they are equals to the same dimension, but I get an error \"EXC_BAD_INSTRUCTION\" on the try.

Here is

3条回答
  •  盖世英雄少女心
    2021-01-16 09:09

    The problem is you're using the closed range operator in your for loop 0...self.rows. This will include the upper bound of the range in the iteration, which in your case is out of bounds and will therefore crash.

    You want to use the half-open range operator ..< instead:

    for row in 0..

    This will iterate up to but not including the upper bound.


    I would also note @MartinR's comment above – defining equality for the matrices to be solely based on the dimensions being the same seems illogical. Remember that equality implies substitutability (i.e if a == b, a and b are interchangeable).

    I would consider changing your == to check both dimensions and values, and then implement your own dimension check in your sumWith method (or create a new method to compare dimensions).

提交回复
热议问题