Home » Swift » Swift – Split Int to its individual digits

Swift – Split Int to its individual digits

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am trying to split an Int into its individual digits, e.g. 3489 to 3 4 8 9, and then I want to put the digits in an Int array.

I have already tried putting the number into a string and then iterating over each digit, but it doesn’t work:

var number = "123456"

var array = [Int]()

for digit in number {
    array.append(digit)
}

Any ideas?

Answers:

Update: Xcode 9 • Swift 4

You can create an array of characters and flatMap them to Int as follow:

let number = "123456"

let array = number.flatMap{Int(String($0))} // [1, 2, 3, 4, 5, 6]

You can also extend the Integer protocol:

extension Int {
    var array: [Int] {
        return String(self).flatMap{ Int(String($0)) }
    }
}

Xcode 8.2.1 • Swift 3.0.2

You can create an array of characters and flatMap them to Int as follow:

let number = "123456"

let array = number.characters.flatMap{Int(String($0))} // [1, 2, 3, 4, 5, 6]

You can also extend the Integer protocol:

extension Int {
    var array: [Int] {
        return String(self).characters.flatMap{ Int(String($0)) }
    }
}

let myInt = 12345

let myIntArray = myInt.array   // [1, 2, 3, 4, 5]

Edit: As suggested by doisk, you can use flatMap also to nest the result.

let intArray = [456, 827]
let nestedInts = intArray.flatMap{$0.array}

print(nestedInts) // [4, 5, 6, 8, 2, 7]

Questions:
Answers:

this code works:

var number = "123456"
var array = number.utf8.map{Int(($0 as UInt8)) - 48}

this might be slower:

var array = number.characters.map{Int(String($0))!}

and if your number is less or equal than Int.max which is 9223372036854775807 here is the fastest variant (and if your number>Int.max you can split your long string that represents your number into 18-digit groups to make this variant work on large strings)

var array2 = [Int]()
var i = Int(number)!
while i > 0 {array2.append(i%10); i/=10}
array2 = array2.reverse()

Questions:
Answers:

You can try this:

var number = "123456"
var array = number.utf8.map{Int($0)-48}

You can make use of the utf8 property of String to directly access the ASCII value of the characters in the String representation of your number.