More than 26 Digit Larger Data Size Integer for Swift

I am Converting numerical string to Int numbers in my Swift Playground in Xcode.

My calculation is getting more than 26 Digits...

e.g. "4444423533331235525555555"

I am getting error nil...

How to fix this?

My code look something like this:

Code Block
let ageString = "4444423533331235525555555"
let ageInt = Int(ageString)
print(ageInt ?? 0)

In Swift the Int type is pointer sized. This means that:
  • On 32-bit systems it can hold a maximum value of 2,147,483,647 (2^31 - 1, 31 not 32 because the value is signed).

  • On 64-bit systems it can hold a maximum value of 9,223,372,036,854,775,807 (2^63 - 1).

The number you’re trying to convert is way larger than the latter, so there’s no way to represent it in a Swift Int.

How you should proceed here depends on your goals. For something like the example you posted, where you’re using an Int to store an age, you should bounds check your input (that is, check that Int(_:) doesn’t return nil). There’s no reasonable scenario where someone’s age can overflow a Int.

However, if the age thing is just an example and in your real program you really need to represent such massive numbers, you have a couple of choices:
  • If you don’t need to maintain precision, you can use a floating point value, that is, Double.

  • If you need massive numbers that are also completely precise, you’ll need to write or acquire a big number library.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
There's another option: Decimal, which can hold 38 decimal digits. And it is included in Apple's Foundation.
Code Block
import Foundation
let ageString = "4444423533331235525555555"
let ageDecimal = Decimal(string: ageString)
print(ageDecimal ?? 0) //-> 4444423533331235525555555


But before going too further, you should better check if you really need 26-digit precision.


More than 26 Digit Larger Data Size Integer for Swift
 
 
Q