连接 Int 的 Swift 数组以创建一个新的 Int [英] Concatenate Swift Array of Int to create a new Int
问题描述
如何将 Array
([1,2,3,4]
) 变成常规的 Int
(<代码>1234代码>)?我可以让它走另一条路(将 Int
拆分为单个数字),但我无法弄清楚如何组合数组,以便数字组成新数字的数字.
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.
推荐答案
这会起作用:
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 中编译:
Or this compiles in more versions of Swift:
(感谢 Romulo BM.)
(Thanks to Romulo BM.)
let digits = [1,2,3,4]
let intValue = digits.reduce(0) { return $0*10 + $1 }
<小时>
注意
此答案假定输入数组中包含的所有 Int 都是数字 -- 0...9 .除此之外,例如,如果要将 [1,2,3,4, 56]
转换为 Int 123456
,则需要其他方法.
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.
这篇关于连接 Int 的 Swift 数组以创建一个新的 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!