Search code examples
swiftswift-playgroundxcplayground

Infix % operator works in Playground, but not in included Swift library


I'm trying to overload the % operator for doubles in Swift. I realize the reason that the two methods on the Double type exist, but truncatingRemainder()'s behavior works fine for my use case.

I'm using Xcode Playgrounds to work through this problem and I thought I had it solved.

infix operator %

func % (left: Double, right: Double) -> Double {
    return left.truncatingRemainder(dividingBy: right)
}

var x = 0.0

for _ in 0...5 {
    print(x)
    x = (x + 1.5) % 5.0
}

print(x)

This works fine and gives me the correct expected behavior.

After this, I tried putting it into a library I am working on. I created a new .swift file, rebuilt the library, ensured the import statement was working (by using other functions/methods in my library) in my Playground, and I get the following errors:

  • Ambiguous operator declarations found for operator
  • Cannot convert value of type '()' to expected argument type 'Double'
  • Operator is not a known binary operator

An Xcode screenshot showing the errors listed above next to the code that's listed above.

Can anyone explain the difference between putting it in my Playground and including it in an imported file?


Solution

  • For the library, you just need to declare your function with public access. no need infix operator %. You are doing operator overloading.

    public func % (left: Double, right: Double) -> Double {
        return left.truncatingRemainder(dividingBy: right)
    }
    

    infix operator needed when you are working on Custom Operator. Like infix operator **