3

I want to convert a positive number into the respective list of digits -- the digits should be Ints as well.

When converting, say 1024, it should return [1,0,2,4]

marco alves
  • 1,707
  • 2
  • 18
  • 28

3 Answers3

10

in Swift 4.1 or above

let number = 1024
let digits = String(number).compactMap { Int(String($0)) }
print(digits) // [1, 0, 2, 4]

in Swift4

let number = 1024
let digits = String(number).flatMap { Int(String($0)) }
print(digits) // [1, 0, 2, 4]

in Swift2 and also Swift3

let number = 1024
let digits = String(number).characters.flatMap { Int(String($0)) }
print(digits) // [1, 0, 2, 4]
ken0nek
  • 517
  • 5
  • 9
2

You don’t need to convert it to an array first. Since strings are collections, you can use the free (non-member) version of map:

map(number) { String($0).toInt() }

But beware your !. If number ever contains a non-numeric digit, your code will crash at runtime. And if the number is negative, it'll start with a "-".

How you want to handle this depends on what you want to do with negative numbers (maybe you want all the digits to be negative). But if you just wanted to ditch the leading "-" you could do something like:

let strNum = number >= 0 ? String(number) : dropFirst(String(number))
let digits = map(strNum) { String($0).toInt()! }

But just in case there's another possible non-numeric character for string representations of integer, you might find it better to do:

let digits = map(String(number)) { String($0).toInt() }.filter { $0 != nil }.map { $0! }
Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
1

After some searching and some trial and error approach using the Swift REPL, I came up with this

var digits:[Int] = Array(String(number)).map { String($0).toInt()! }

Note that the !is critical

marco alves
  • 1,707
  • 2
  • 18
  • 28
  • Just wondering, could you do something like what the top answer suggests here: [String to array](http://stackoverflow.com/questions/25921204/convert-swift-string-to-array) – CyanogenCX Jan 02 '15 at 01:17
  • 2
    Oops sorry, misread you post originally as wanting to convert a string rather than a int to digits – have deleted my answer as yours is good and the `!` should be safe. But you can skip the `Array` conversion if you use the non-member map: `map(String(number)) { String($0).toInt()! }` – Airspeed Velocity Jan 02 '15 at 02:31
  • 1
    Aha – except I was forgetting about negative numbers, so there is still a risk of crashing. Just goes to show you can never underestimate the danger of `!`... – Airspeed Velocity Jan 02 '15 at 15:20
  • updated for Swift 2: `var digits:[Int] = Array(String(number).characters).map { String($0).toInt()! }` – Lorenzo Aug 05 '15 at 22:16