Why Strideable does not declare operators '+' and '-'?

In the Swift standard library, we have Strideable proto incorporated two methods:

func distance(to other: Self) -> Self.Stride
func advanced(by n: Self.Stride) -> Self

It would be natural to have defining operators in a like manner:

extension Strideable {
    static func +(lhs: Self, rhs: Self.Stride) -> Self {
        return lhs.advanced(by: rhs)
    }

    static func -(lhs: Self, rhs: Self.Stride) -> Self {
        return lhs.advanced(by: -rhs)
    }

    static func -(lhs: Self, rhs: Self) -> Self.Stride {
        return lhs.distance(to: rhs)
    }
}

Unfortunately, this is true only for pointers (UnsafePointer, UnsafeRawPointer, ...) which conform _Pointer protocol implicitly, which inherits from Stridable.
Assumption for restricted declaration looks like to avoid conflicts in some parts of code. Does anybody know the true reason for not defining these methods for all conformed Strideable?

2 Likes

This isn't the reason, but it would pollute the operator space with heterogeneous operations. E.g. UInt8.Stride is Int, so if these overloads existed, you'd be able to do UInt8 + Int, despite mixed-type integer arithmetic generally not being provided in Swift, and UInt8 - UInt8 would sometimes be UInt8 and sometimes Int depending on context.

21 Likes