将Swift整数数组连接起来以创建一个新的整数。

6

如何将一个Array<Int>[1,2,3,4])变成普通的Int1234)?我知道可以将一个Int拆分成单个数字,但是我不知道该如何组合数组,使数字组成一个新的数字。

5个回答

16

这将有效:

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,则需要使用其他方法。


1
我尝试用以下数组[1,2,3,4, 56],但它给出了12396,所以我认为这可能不适用于具有多位数的int值。 - Prientus
这个答案是针对每个Int表示十进制数字的情况而设计的。我认为将其命名为“digits”可以表达我的答案要求... - OOPer
我明白了。我以为这个问题是关于一种更通用的方法来将 Int 数组(任意位数)合并成一个数组,而不是特别是将 Int 数组“转换回”单个整数。 - Prientus
@Prientus,再次阅读问题,原帖并没有清楚地说明要求。作者应该考虑读者的想法。我会在我的回答中添加一些关于要求的注释。谢谢。 - OOPer

4
你也可以进行字符串转换:

您也可以进行字符串转换:

Int(a.map(String.init).joined())

1

你也可以这样做

let digitsArray = [2, 3, 1, 5]
if let number = Int.init(d.flatMap({"\($0)"}).joined()) {
    // do whatever with <number>
}

0

又一种解决方案

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
}

这段代码要求 `nums` 数组仅包含非负整数。

0
let number = [1, 2, 3].reduce(0){ $0 * 10 + $1 }

print("result: \(number)") // result: 123

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接