-2

I have an [Int] array like so:

[1, 2, 3]

How can I apply a function on this so it returns:

123

?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Zorgan
  • 8,227
  • 23
  • 106
  • 207

2 Answers2

1

We can do like below...

var finalStr = ""
    [1,2,3].forEach {
        finalStr.append(String($0))
    }
    if let number = Int(finalStr) {
        print(number)
    }
Mahendra
  • 8,448
  • 3
  • 33
  • 56
1
let nums = [1, 2, 3]
let combined = nums.reduce(0) { ($0*10) + $1 }
print(combined)

Caveats

  • Make sure the Int won't overflow if the number gets too long (+263 on a 64-bit system).
  • You need to also be careful all numbers in the list aren't more than 9 (a single base-10 digit), or this arithmetic will fail. Use the String concatenation technique to ensure that all base-10 numbers are correctly handled. But, again, you need to be careful that the number won't overflow if you choose to convert it back to an Int.
Bradley Mackey
  • 6,777
  • 5
  • 31
  • 45