[SR-2162] distance(to:) isn't a proper distance function and frequently leads to bugs in calling code #44770
Labels
improvement
standard library
Area: Standard library umbrella
swift evolution proposal needed
Flag → feature: A feature that warrants a Swift evolution proposal
Environment
(Swift 2.x)...
Additional Detail from JIRA
md5: 2968ca3980b3e3f76c373ea465850d66
Issue Description:
A distance function conventionally has the property that
d(x,y) ≥ 0
. For example, you'd say that the distance between 3 and 5 on a number line is +2, and you'd say the distance between 5 and 3 on a number line is +2 (not -2).However, if you call Swift's
distance(to:)
function on anInt
, you get signed values depending on the ordering of arguments:This can be unexpected, and has let to bugs in Apple's open source XCTest implementation. In some robotics code I've been working on, we almost always wrap calls to
distance(to:)
withabs
for this reason, and forgetting a call toabs
can lead to serious bugs.While
distance(to:)
's behavior is unexpected and can lead to bugs in calling code, its implementation makes sense given its description in theStrideable
protocol:For the above to hold for any two integers,
distance(to:)
has to return negative distances. Unfortunately, usingdistance
in the name also implies it is a proper distance function where in fact it is not.I see two ways this could be fixed:
1. Change the behavior of
distance(to:)
to return proper, unsigned distances. This would change the behavior of and break existing code.2. Rename
distance(to:)
tooffset(to:)
ordisplacement(to:)
to clarify it does not actually return an unsigned distance, but a displacement or offset. A fix-it could be provided to help rename and migrate existing code.The text was updated successfully, but these errors were encountered: