2

Is it possible to get all digits of the Int variable in the Swift not converting this variable to the string ?

Small example how i am doing this now:

let number = 123456

let array = String(number).characters.map{Int(String($0)) ?? 0}
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100

1 Answers1

5

Something like this?

var number = 123456
var array = [Int]()

while number > 0 {
    array.append(number % 10)
    number = number / 10
}
array.reverse()
Idan
  • 5,405
  • 7
  • 35
  • 52
  • 2
    Here's a one-liner, though it's probably less efficient than your original: `let array = (0...Int(ceil(log10(Float(number)))) - 1).reversed().map{(number / Int(NSDecimalNumber(decimal: pow(10, $0)))) % 10}` – sudo Nov 22 '16 at 08:35