简体   繁体   中英

CoreData rewards by sum of an attribute rather than individual records

I am working on an app that rewards users when they record a walk, bike ride or bus ride. They are rewarded after a distance reached per journey but I would like to reward them for the total (sum) distance they have recorded with the app using CoreData .

I have tried to look at other Stack Overflow questions on the same topic but have been unsuccessful so far

for journey in journeys where journey.distance > reward.distance {
         if earned == nil {
          earned = journey
        }

It is a bit confusing what you are asking for. To check if sum of some elements is greater than some value it might be best to use reduce in swift. Something like the following:

private func checkRewardAchieved(_ reward: Reward, withJourneys journeys: [Journey]) -> Bool {
    return journeys.reduce(0.0, { $0 + $1.distance }) >= reward.distance
}

Here journeys.reduce(0.0, { $0 + $1.distance }) will return a sum of all distances in your array. The sum is then compared to rewards >= reward.distance and result is either true or false.

It might be nice to compute the sum directly with core data though. To do so this answer looks promising.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM