Using multiple dispatch to add different types of numbers


Airspeed Velocity

This is part of a series on solving Paul Graham’s accumulator problem in Swift. You can find Part 1 here.

In the previous post, we solved the requirement that our accumulator accept any kind of numeric type, and to “upgrade” the type it returns from an integer to floating point only the first time it is called with a floating point number. The solution was to use the Swift Any type:

There were lots of flaws with this approach, the worst of which was the loss of type-safety that comes with using Any. The user of foo can pass anything into the accumulator – a String, a Range, any user-defined Class. Our solution to this was to have incf return nil for types it didn’t understand. But it would be much better to rewrite foo so that it just wasn’t possible to call it with an unsuitable…

View original post 465 more words