Search code examples
swiftnsdecimalnumber

Trying to reduce Decimal property gives: Type of expression is ambiguous without more context


I have a Core Data Entity called Transaction with the property value of type Decimal.

I'm trying to reduce an array of Transactions, to sum the value attribute:

private var transactions = [Transaction]() {
    didSet {
        navigationItem.title = transactions.reduce(0.0) { $0.decimalNumberByAdding($1.value) }
    }
}

But this gives compiler error: Type of expression is ambiguous without more context

How can I reduce an array of objects by summing an Decimal property?


Solution

  • Figured out that despite the type on my data model was set to Decimal, actually the type is NSDecimalNumber.

    enter image description here

    So it had to be:

    let total = transactions.reduce(NSDecimalNumber(decimal: 0)) { $0.adding($1.value ?? NSDecimalNumber(decimal: 0)) }
    navigationItem.title = "$ \(total)"