marco alves marco alves - 1 year ago 80
Swift Question

How convert a *positive* number into an array of digits in Swift

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]

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download