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

后端 未结 5 605
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:25

    Bring back the simple modulo syntax in swift 3:

    This syntax was actually suggested on Apples official swift mailing list here but for some reason they opted for a less elegant syntax.

    infix operator %%/*<--infix operator is required for custom infix char combos*/
    /**
     * Brings back simple modulo syntax (was removed in swift 3)
     * Calculates the remainder of expression1 divided by expression2
     * The sign of the modulo result matches the sign of the dividend (the first number). For example, -4 % 3 and -4 % -3 both evaluate to -1
     * EXAMPLE: 
     * print(12 %% 5)    // 2
     * print(4.3 %% 2.1) // 0.0999999999999996
     * print(4 %% 4)     // 0
     * NOTE: The first print returns 2, rather than 12/5 or 2.4, because the modulo (%) operator returns only the remainder. The second trace returns 0.0999999999999996 instead of the expected 0.1 because of the limitations of floating-point accuracy in binary computing.
     * NOTE: Int's can still use single %
     * NOTE: there is also .remainder which supports returning negatives as oppose to truncatingRemainder (aka the old %) which returns only positive.
     */
    public func %% (left:CGFloat, right:CGFloat) -> CGFloat {
        return left.truncatingRemainder(dividingBy: right)
    }
    

    This simple swift 3 migration tip is part of a more comprehensive swift 3 migration guide with many insights (35k loc / 8-days of migration) http://eon.codes/blog/2017/01/12/swift-3-migration/

提交回复
热议问题