user190494 user190494 - 7 months ago 30
Swift Question

How to convert from octal to decimal in swift

Hi I am trying to convert an octal number to decimal in swift. What would be the easiest way to do this?


From Octal to Decimal

There is a specific Int initializer for this

let octal = 10
if let decimal = Int(String(octal), radix: 8) {
    print(decimal) // 8

From Decimal to Octal

let decimal = 8
if let octal = Int(String(decimal, radix: 8)) {
    print(octal) // 10

Note 1: Please pay attention: parenthesis are different in the 2 code snippets.

Note 2: Int initializer can fail for string representations of number with more exotic radixes. Please read the comment by @AMomchilov below.