How to split an Int to its individual digits?
A solution without having to convert the int to string....
Example
1234%10 = 4 <-
1234/10 = 123
123%10 = 3 <-
123/10 = 12
12%10 = 2 <-
12/10 = 1
1%10 = 1 <-
var num = 12345
var arrayInt = [Int]()
arrayInt.append(num%10)
while num >= 10 {
num = num/10
arrayInt.insert(num%10, at: 0)
}
We can also extend the StringProtocol and create a computed property:
edit/update: Xcode 11.5 • Swift 5.2
extension StringProtocol {
var digits: [Int] { compactMap(\.wholeNumberValue) }
}
let string = "123456"
let digits = string.digits // [1, 2, 3, 4, 5, 6]
extension LosslessStringConvertible {
var string: String { .init(self) }
}
extension Numeric where Self: LosslessStringConvertible {
var digits: [Int] { string.digits }
}
let integer = 123
let integerDigits = integer.digits // [1, 2, 3]
let double = 12.34
let doubleDigits = double.digits // // [1, 2, 3, 4]
In Swift 5 now we can use the new Character
property wholeNumberValue
let string = "123456"
let digits = string.compactMap{ $0.wholeNumberValue } // [1, 2, 3, 4, 5, 6]