Reputation: 438
Quick question. My array is thus:
OutsideIncome(userName: "Beth", allOthers: 0, babysitting: 0, houseCleaning: 0, mowingLawns: 0, summerJobs: 0),
OutsideIncome(userName: "Molly", allOthers: 0, babysitting: 0, houseCleaning: 0, mowingLawns: 0, summerJobs: 0)
One element is a String
, and the rest are Ints
. How would I go about getting the sum of the Ints?
Code I've tried:
#1: FOR LOOP - didn't work
for item in OutsideIncome.incomeArray.filter({ $0.userName != self.currentUserName }).reduce(0 , { $0 + $1 }) {
tempOutsideIncome = item.allOthers + item.babysitting + item.houseCleaning + item.mowingLawns + item.summerJobs
}
#2: FILTER REDUCE - didn't work
let outsideIncome = OutsideIncome.incomeArray.filter({ $0.userName != self.currentUserName })
outsideIncome.reduce(0, { $0 + $1 })
#3: FILTER - works but is cumbersome. There has to be a simpler way.
let tempArray = OutsideIncome.incomeArray.filter({ $0.userName == self.currentUserName })
let tempOutsideSum = (tempArray.first?.allOthers)! + (tempArray.first?.babysitting)! + (tempArray.first?.houseCleaning)! + (tempArray.first?.mowingLawns)! + (tempArray.first?.summerJobs)!
I'm thinking there's some way to map
it or filter
reduce
it, but I can't figure it out.
Anyone have a solution?
UPDATE:
Thanks for the answer. My final code:
struct OutsideIncome {
let userName: String
let allOthers: Int
let babysitting: Int
let houseCleaning: Int
let mowingLawns: Int
let summerJobs: Int
// create 'computed property'
var totalJobs: Int {
return allOthers +
babysitting +
houseCleaning +
mowingLawns +
summerJobs
}
}
let currentUserName = "Beth"
let array = [OutsideIncome(userName: "Beth", allOthers: 1, babysitting: 0, houseCleaning: 0, mowingLawns: 0, summerJobs: 0),
OutsideIncome(userName: "Molly", allOthers: 0, babysitting: 0, houseCleaning: 0, mowingLawns: 0, summerJobs: 0)]
let result = array.filter({ $0.userName == user.firstName }).reduce(0, { $0 + $1.totalJobs })
}
Upvotes: 0
Views: 32
Reputation: 310
Create a computed property
var totalJobs: Int {
return allOthers +
babysitting +
houseCleaning +
mowingLawns +
summerJobs
}
Then you can chain filter and reduce
let result = array.filter { $0.userName == currentUserName}.reduce(0) { (res, item) -> Int in
return res + item.totalJobs
}
Upvotes: 2