I have an Entity named: Transaction
and an Attribute named: amount
. I would like to declare an array from amount
attribute that can using the summing an array sample code
sum = array_name.reduce(0,+)
I am trying to do this way to declare an array from Attribute
var amountArray =
(self.transactionsArray as NSArray).value(forKey: "amount") as! NSArray
sum = amountArray.reduce(0,+)
but it's not working and throw the error
Ambiguous reference to member '+'
Using Swift 4, @MartinR's suggestion should work. If it doesn't, you should provide more information about your code, maybe specifically about the details of Transaction
, the type of the amount
variable, and about the exact nature of transactionsArray
.
Assuming that transactionsArray
is declared as the non-optional [Transaction]
and that amount
is one of the Core Data numeric types,
let sum = transactionsArray.reduce(0) { $0 + $1.amount }
...is correct. You might make it slightly more explicit by declaring the type of sum
:
let sum : Double = transactionsArray.reduce(0) { $0 + $1.amount }
(Make sure to use the same type as amount
here, I'm just guessing Double
).
It's possible to get the sum with an NSArray
and the @sum
operator, for example
if let sum = (transactionsArray as NSArray).value(forKeyPath:"@sum.amount") as? Double {
....
}
The as? Double
as? Double
is needed because of the lack of type info on NSArray
that @vadian mentioned.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.