What does “% is unavailable: Use truncatingRemainder instead” mean?

后端 未结 5 576
Happy的楠姐
Happy的楠姐 2020-12-12 18:44

I get the following error when using code for an extension, I\'m not sure if they\'re asking to just use a different operator or modify the values in the expression based on

5条回答
  •  醉梦人生
    2020-12-12 19:11

    There's no need to create a separate modulo operator for floating point numbers, unless you think it makes the code safer. You can overload the % operator to accept floating point numbers like so:

    func %(lhs: N, rhs: N) -> N {
        lhs.truncatingRemainder(dividingBy: rhs)
    }
    

    Usage

    let a: Float80 = 10
    let b: Float80 = 3
    print(a % b)
    

    You can now use % with any two floating point numbers of the same tye.

提交回复
热议问题