如何在Swift中求和NSNumber数组?

时间:2017-11-19 07:38:07

标签: swift

如何在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] 

2 个答案:

答案 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, +)