[swift-users] Modulo operation in Swift?

Martin R martinr448 at gmail.com
Thu Nov 9 06:51:04 CST 2017

There was a discussion in swift-evolution, starting at


about adding a "true modulo" operator to the standard library. There were different opinions whether

- such a thing needs to be in the standard library at all, and if yes:
- if it should be an operator or function,
- how it should be named.

As far as I know, nothing happened until now. The above posting contains a possible (Swift 3) implementation. In Swift 4 that would be

    infix operator %%: MultiplicationPrecedence

    func %%<T: BinaryInteger>(lhs: T, rhs: T) -> T {
        return (lhs % rhs + rhs) % rhs

I would probably do (as an operator or as a function)

    func %%<T: BinaryInteger>(lhs: T, rhs: T) -> T {
        let rem = lhs % rhs // -rhs <= rem <= rhs
        return rem >= 0 ? rem : rem + rhs

with one division instead of two.

Regards, Martin

> Am 09.11.2017 um 12:43 schrieb Jens Persson via swift-users <swift-users at swift.org>:
> Hi all!
> Is there a modulo operation/function in Swift? I want the "true" mathematical modulo (as % in Python), and not remainder (as % in Swift).
> Do I have to implement this basic mathematical function myself and if so what is the best way to write it (it will be heavily used so I want it to be as fast as possible)?
> /Jens
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

More information about the swift-users mailing list