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.
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.
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.
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.
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] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With