In Swift currently, the /
operator is used to handle floating point and integer division, depending on the types of the operands. This seems rather natural but can lead to bugs (example below). In some other languages, such as python, there are separate operators for integer division and floating point division. This would allow for compile time errors and more readable code.
For the sake of this argument I'm going to copy python's operators:
/
for floating point division
//
for integer division
Imagine you have a class:
class View {
let animationDuration: Float = 0.3 // seconds
func animate() {
UIView.animate(withDuration: TimeInterval(animationDuration), ...)
}
}
Later, a someone decides that this animationDuration
should be in milliseconds, and notices that it can be an Int
instead of a Float
.
class View {
let animationDuration: Int = 300 // milliseconds
func animate() {
UIView.animate(withDuration: TimeInterval(animationDuration/1000), ...)
}
}
In this example TimeInterval is an alias for a Double.
Do you see the bug? It should be written as TimeInterval(animationDuration)/1000
as it is first doing integer division (in this case the result would be 0) and then converting to a TimeInterval. It is a silly mistake but it is one that is easy to make and could be improved by using separate operators. If this were using my proposal, both would use floating point division. I find that in applications floating point division is much more common than integer division.
In other cases where you do want integer division, you could write something like this:
class Foo {
let a: Int
let b: Int
func doSomething() {
...
let c = a // b
...
}
}
Which gives the reader a better picture of your intentions in a big class, and they don't have to look at the types of a
and b
to know what you intended. Later if someone decides that b
should be a floating point number, they would get a compile time error as they tried to do integer division with a floating point number.