6

How can you make an Array<Int> ([1,2,3,4]) into a regular Int (1234)? I can get it to go the other way (splitting up an Int into individual digits), but I can't figure out how to combine the array so that the numbers make up the digits of a new number.

jscs
  • 63,694
  • 13
  • 151
  • 195
Vikings1028
  • 61
  • 1
  • 3

5 Answers5

16

This will work:

let digits = [1,2,3,4]
let intValue = digits.reduce(0, combine: {$0*10 + $1})

For Swift 4+ :

let digits = [1,2,3,4]
let intValue = digits.reduce(0, {$0*10 + $1})

Or this compiles in more versions of Swift:

(Thanks to Romulo BM.)

let digits = [1,2,3,4]
let intValue = digits.reduce(0) { return $0*10 + $1 }

NOTE

This answer assumes all the Ints contained in the input array are digits -- 0...9 . Other than that, for example, if you want to convert [1,2,3,4, 56] to an Int 123456, you need other ways.

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • 1
    I tried this with the following array [1,2,3,4, 56] and it gave me 12396 so I believe this might not work with int values with more than one digit – Prientus Feb 08 '17 at 20:37
  • This answer is dedicated for the case each Int is representing a single digit of decimal number. I thought naming `digits` was expressing the requirement for my answer... – OOPer Feb 08 '17 at 20:42
  • I see. I assumed the question was for a more generic way to combine Int arrays (of any number of digits) to one. Not specifically for converting an Int Array *back* to an single Integer. – Prientus Feb 08 '17 at 20:48
  • @Prientus, reading the question again, the OP is not clear enough about the requirement. The writers should consider how readers would think. I will add some note about the requirement of my answer. Thanks. – OOPer Feb 08 '17 at 20:51
4

You can go through string conversion too:

Int(a.map(String.init).joined())
Alistra
  • 5,177
  • 2
  • 30
  • 42
1

You could also do

let digitsArray = [2, 3, 1, 5]
if let number = Int.init(d.flatMap({"\($0)"}).joined()) {
    // do whatever with <number>
}
gabuchan
  • 785
  • 1
  • 7
  • 18
0

Just another solution

let nums:[UInt] = [1, 20, 3, 4]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
    print(value)
}

This code also works if the values inside the nums array are bigger than 10.

let nums:[UInt] = [10, 20, 30, 40]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
    print(value) // 10203040
}

This code required the nums array to contain only non negative integers.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
0
let number = [1, 2, 3].reduce(0){ $0 * 10 + $1 }

print("result: \(number)") // result: 123
ovo
  • 1,904
  • 13
  • 26