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.
问题:
回答1:
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.
回答2:
You can go through string conversion too:
Int(a.map(String.init).joined())
回答3:
edit/update: Swift 4 or later
If your collection of integers has only single digits elements I suggest using the awesome solution provided by @OOper.
If you would like to join a regular collection of integers into a single integer you would first need to know how to check the number of digits of each integer:
extension BinaryInteger {
var numberOfDigits: Int {
return self != 0 ? Int(log10(abs(Double(self)))) + 1 : 1
}
}
Then you can accumulate the total based on the number of digits of each element:
extension Collection where Element: BinaryInteger {
var digitsSum: Int { return reduce(0, { $0 + $1.numberOfDigits }) }
func joined() -> Int? {
guard digitsSum <= Int.max.numberOfDigits else { return nil }
// (total multiplied by 10 powered to number of digits) + value
return reduce(0) { $0 * Int(pow(10, Double($1.numberOfDigits))) + Int($1) }
}
}
let numbers = [1,2,3,4,56]
let value = numbers.joined() // 123456
回答4:
Just another solution
let nums:[UInt] = [1, 20, 3, 4]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
print(value)
}
This code also works if the values inside the nums
array are bigger than 10
.
let nums:[UInt] = [10, 20, 30, 40]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
print(value) // 10203040
}
This code required the
nums
array to contain only non negative integers.
回答5:
let number = [1, 2, 3].reduce(0){ $0 * 10 + $1 }
print("result: \(number)") // result: 123
回答6:
You could also do
let digitsArray = [2, 3, 1, 5]
if let number = Int.init(d.flatMap({"\($0)"}).joined()) {
// do whatever with <number>
}