如何将一个Array<Int>
([1,2,3,4]
)变成普通的Int
(1234
)?我知道可以将一个Int
拆分成单个数字,但是我不知道该如何组合数组,使数字组成一个新的数字。
这将有效:
let digits = [1,2,3,4]
let intValue = digits.reduce(0, combine: {$0*10 + $1})
对于 Swift 4+:
let digits = [1,2,3,4]
let intValue = digits.reduce(0, {$0*10 + $1})
或者这可以在更多版本的Swift中编译:
(感谢Romulo BM。)
let digits = [1,2,3,4]
let intValue = digits.reduce(0) { return $0*10 + $1 }
注意
本回答假定输入数组中包含的所有整数都是数字0...9。除此之外,例如,如果您想将[1,2,3,4,56]
转换为整数123456
,则需要使用其他方法。
您也可以进行字符串转换:
Int(a.map(String.init).joined())
你也可以这样做
let digitsArray = [2, 3, 1, 5]
if let number = Int.init(d.flatMap({"\($0)"}).joined()) {
// do whatever with <number>
}
又一种解决方案
let nums:[UInt] = [1, 20, 3, 4]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
print(value)
}
如果nums
数组中的值大于10
,此代码也能正常工作。
let nums:[UInt] = [10, 20, 30, 40]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
print(value) // 10203040
}
let number = [1, 2, 3].reduce(0){ $0 * 10 + $1 }
print("result: \(number)") // result: 123