如何在Swift中求和NSNumber数组?我使用.reduce
时收到此错误。任何其他方式来总结NSNumber数组?
无法使用类型'(Int,_)
的参数列表调用'reduce'
var record = [Record]()
var incomeFilter: [Record] = []
let formatter = NumberFormatter()
formatter.numberStyle = .currencyAccounting
formatter.currencySymbol = "¥"
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
incomeFilter = record.filter { $0.recordtype!.contains("Income") && $0.createdAt! == recordItem.createdAt!}
let incomeSumArray = incomeFilter.map{formatter.number(from: $0.amount!) ?? 0.00}.reduce(0, +)
//Cannot invoke 'reduce' with an argument list of type '(Int, _)
print(incomeSumArray)
//result without .reduce
//[9.99, 6.58, 7777.77]
答案 0 :(得分:3)
我认为问题是?? 0
使用NSNumber
类型的可选项。 nil-coalescing时总是需要相同的类型。您必须先将NSNumber
转换为数值(double
):
let incomeSum = incomeFilter
.map {
formatter.number(from: $0.amount!)?.doubleValue ?? 0
}
.reduce(0, +)
或
let incomeSum = incomeFilter
.map {
guard
let amountString = $0.amount,
let number = formatter.number(from: amountString)
else {
return 0
}
return number.doubleValue
}
.reduce(0, +)
答案 1 :(得分:0)
您可以在减少它之前将incomeFilter
映射为双精度数组(incomeFilter.map{formatter.number(from: $0.amount!) ?? 0.00}
):
let incomeSumArray = incomeFilter.map {
formatter.number(from: $0.amount!) ?? 0.00
}.map {
$0.doubleValue
}.reduce(0, +)