0

How to sum NSNumber array in Swift? I'm getting this error when I use .reduce. any other way to sum the NSNumber array?

Cannot invoke 'reduce' with an argument list of type '(Int, _)

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
  • Once again, why don't you first sum up the Double values and then use the number formatter and I explained the error message in my answer yesterday Commented Nov 19, 2017 at 7:55
  • I think I can't sum the double first, because some string have separator "," , so if I sum the double first, the number which above 1,000 will get nil. The separator break the string to double conversion routine. @vadian Commented Nov 19, 2017 at 8:04

2 Answers 2

3

I think the problem is using ?? 0 with an optional of type NSNumber. You always need the same type when nil-coalescing. You have to convert NSNumber to a numeric value (double) first:

let incomeSum = incomeFilter
    .map {
        formatter.number(from: $0.amount!)?.doubleValue ?? 0
     }
    .reduce(0, +)

or

let incomeSum = incomeFilter
    .map {
        guard
           let amountString = $0.amount,
           let number = formatter.number(from: amountString)
        else {
           return 0
        }

        return number.doubleValue
     }
    .reduce(0, +)  
Sign up to request clarification or add additional context in comments.

Comments

0

You could map the incomeFilter to be an array of doubles (incomeFilter.map{formatter.number(from: $0.amount!) ?? 0.00}) before reducing it:

let incomeSumArray = incomeFilter.map {
        formatter.number(from: $0.amount!) ?? 0.00
    }.map {
        $0.doubleValue
    }.reduce(0, +)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.