iosswiftswift3nsdecimalnumber

Swift 3 : Decimal to Int


I tried to convert Decimal to Int with the follow code:

Int(pow(Decimal(size), 2) - 1) 

But I get:

.swift:254:43: Cannot invoke initializer for type 'Int' with an argument list of type '(Decimal)' 

Here I know pow is returning a Decimal but it seems that Int has no constructors and member functions to convert Decimal to Int.
How can I convert Decimal to Int in Swift 3?


Solution

  • This is my updated answer (thanks to Martin R and the OP for the remarks). The OP's problem was just casting the pow(x: Decimal,y: Int) -> Decimal function to an Int after subtracting 1 from the result. I have answered the question with the help of this SO post for NSDecimal and Apple's documentation on Decimal. You have to convert your result to an NSDecimalNumber, which can in turn be casted into an Int:

    let size = Decimal(2)
    let test = pow(size, 2) - 1
    let result = NSDecimalNumber(decimal: test)
    print(Int(result)) // testing the cast to Int