Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Swift Array of Int to create a new Int

Tags:

arrays

int

swift

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.

like image 536
Vikings1028 Avatar asked Jul 03 '16 00:07

Vikings1028


People also ask

How do you concatenate an int array?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do I merge one array to another in Swift?

var Array1 = ["Item 1", "Item 2"] var Array2 = ["Thing 1", "Thing 2"] var Array3 = Array1 + Array2 // Array 3 will just be them combined :) Save this answer.

How do you append to an array in Swift?

To append another Array to this Array in Swift, call append(contentsOf:) method on this array, and pass the other array for contentsOf parameter. append(contentsOf:) method appends the given array to the end of this array.

How do I initialize an array in Swift?

To initialize a set with predefined list of unique elements, Swift allows to use the array literal for sets. The initial elements are comma separated and enclosed in square brackets: [element1, element2, ..., elementN] .


1 Answers

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.

like image 124
OOPer Avatar answered Sep 25 '22 20:09

OOPer