-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
  • 45,571
  • 9
  • 73
  • 100
Zorgan
  • 6,953
  • 16
  • 88
  • 175

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
  • 7,791
  • 2
  • 31
  • 52
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
  • 4,703
  • 4
  • 26
  • 40