0

I like to know, How can I declare and initialize a constant bigger than UInt64 in Swift? Swift infer seems unable to work for down number. How I should solve this issue?

let number = 11111111222222233333333344444445555555987654321 // Error: overflow
print(number, type(of: number))
koen
  • 5,383
  • 7
  • 50
  • 89
ios coder
  • 1
  • 4
  • 31
  • 91

1 Answers1

3

Decimal is the numeric type capable of holding the largest value in Swift. However,you can't declare a Decimal literal, since integer literals are inferred to Int, while floating point literals are inferred to Double, so you need to initialise the Decimal from a String literal.

let number = Decimal(string: "321321321155564654646546546546554653334334")!

From the documentation of NSDecimalNumber (whose Swift version is Decimal and hence their numeric range is equivalent):

An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

If you need to be able to represent arbitrary-length numbers in Swift, you need to use a 3rd party library (or create one yourself), there's no built-in type that could handle this in Swift.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • I tried your given code: the result is not correct. 11111111222222233333333344444445555555900000000 NSDecimal – ios coder Nov 18 '20 at 09:51
  • @Omid how did you get that? If I print the result I do get the correct number (as expected) – Dávid Pásztor Nov 18 '20 at 09:53
  • @Omid that number cannot be represented as a `Decimal`, since it overflows even `Decimal`. `Decimal` can only have 38 leading digits that are non-zero, and the `Decimal(string:)` init seems to keep exactly that many digits, then just initializes the remaining digits as 0. If you need that many digits, you'll need to use a 3rd party library that can represent arbitrary-length numbers in Swift. – Dávid Pásztor Nov 18 '20 at 14:48