Dealing with large numbers in Swift

Type inference is a handy feature in Swift that makes declaring most variables fun and easy. However, there are cases when you must explicitly define the type of the variable.

In this example, the starting point is having 4 big numbers, each consisting of 50 digits. Normally you might try to put them into a variable with type inference, like this:

var numbers =
    [37107287533902102798797998220837590246510135740250,
    46376937677490009712648124896970078050417018260538,
    74324986199524741059474233309513058123726617309629,
    91942213363574161572522430563301811072406154908250]

Since the compiler is getting an integer like number fed to it, it tries to automatically use the type Int (Int64 on a 64-bit platform, Int32 on a 32-bit platform). This leads to a compile-time error of an overflow. Since the numbers are too big even for an UInt64 type, we must use floating point here. With floating point there is less precision, but let’s not worry too much about that right now.

var numbers : Double[] =
[37107287533902102798797998220837590246510135740250,
    46376937677490009712648124896970078050417018260538,
    74324986199524741059474233309513058123726617309629,
    91942213363574161572522430563301811072406154908250]

Now the code compiles!

If you want to calculate the sum of these, you can simply do the following:

var sum : Double = 0
for number in numbers
{
    sum += number
}
sum

As you see here I must again explicitly define the “sum” variable to be of type Double due to the size of the numbers being calculated. However, I can use type inference in the for-in loop for the constant called “number” since the numbers array is already of type Double[].

 
56
Kudos
 
56
Kudos

Now read this

The Road To 1000 Downloads

Today is a day of celebration, the cumulative downloads of my 3 iOS games broke the one thousand mark arriving at 1005 downloads! It is exactly 153 days since the release of the first game. I don’t know how representative this is of an... Continue →