Do2 Do2 - 5 months ago 122
Swift Question

Swift - Split Int to its individual digits

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?

Answer

Update: Xcode 7.0.1 • Swift 2.0

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

let number = "123456"

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


extension Int {
    var array: [Int] {
        return description.characters.map{Int(String($0)) ?? 0}
    }
}

let myInt = 12345

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

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

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

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