I have an [Int]
array like so:
[1, 2, 3]
How can I apply a function on this so it returns:
123
?
I have an [Int]
array like so:
[1, 2, 3]
How can I apply a function on this so it returns:
123
?
We can do like below...
var finalStr = ""
[1,2,3].forEach {
finalStr.append(String($0))
}
if let number = Int(finalStr) {
print(number)
}
let nums = [1, 2, 3]
let combined = nums.reduce(0) { ($0*10) + $1 }
print(combined)
Caveats
Int
won't overflow if the number gets too long (+263 on a 64-bit system).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
.