[swift-evolution] Epic: Typesafe calculations

Tino Heth 2th at gmx.de
Thu Dec 24 06:28:41 CST 2015


Hi there,

this is a kind of survey for general interest that could lead to several separate proposals — at least one would address a real-world problem with evident fatal consequences (or instead of proposals, we might end up with clever patterns to handle the problems better).

Right now, it's possible to do type-safe math with Swift, but afaics, it is impractical because the language lacks support for this.

Let's say I want to express the concepts of temperature and mass.
I can declare
let t: Float = 100.0
let m: Float = 1
and work with those — but the values are just plain numbers, and can be used in a way that makes no sense (addition of temperature and mass, for example)

We can't subclass structs like Float, and typealias has very limited use, because it's really just what it says: A new name without special features that can be used mutually interchangeable with the "real" type.

A first tiny step towards more safety would be empowering typealias and generate warnings when a function is used with the "wrong" parameter type ("Kelvin" requested, but plain Float given).
Additionally, extensions written for a typealias shouldn't be treated like extensions for the underlying type.
An extra benefit of this would be the possibility to have
typealias Path = String
and make a clean distinction between general String-methods and those that are only relevant for Strings that represent a Path in the file system — it would even be possible to generate failable initializers to document constraints of the "new" type.

I know that issues because of wrong units are something the average iOS-developer seldom cares for, but as I said above:
Bugs that only could happen because of missing typesafety in calculations caused disasters that make memory leaks and race conditions look ridiculous trivial.

Originally, I planned to broaden the topic much more than I did, but as community reaction sometimes is quite mysterious to me, focusing on one aspect might be better…

So, any opinions, or even arguments against typesafe math?

Merry christmas!
Tino


More information about the swift-evolution mailing list