user190494 - 1 year ago 76

Swift Question

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

Answer Source

There is a specific `Int`

initializer for this

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

```
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@AMomchilovbelow.