Reputation: 159
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:
Can anyone explain the difference between putting it in my Playground and including it in an imported file?
Upvotes: 1
Views: 77
Reputation: 18914
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 **
Upvotes: 1