Project/ReceiptMind
💰 Swift reduce 완전 정복: totalAmount() 메서드로 배우는 누적 합계 계산
밤새는 탐험가89
2025. 8. 3. 22:10
728x90
SMALL
앞서 살펴본 filteredTransactions 함수는 특정 타입과 날짜에 해당하는 거래 내역만 골라내는 데 사용되었습니다.
이번에는 그 필터링된 거래들을 합산해서 누적 금액을 계산하는 totalAmount() 메서드를 소개하려고 합니다.
📦 함수 선언
func totalAmount(
type: TransactionType,
in date: Date,
granularity: Calendar.Component = .month
) -> Int {
let filtered = filteredTransactions(type: type, in: date, granularity: granularity)
return filtered.reduce(0) { $0 + $1.amount }
}
🧭 이 함수는 무슨 일을 하나요?
이 함수는 다음을 수행합니다:
- 특정 날짜 범위와 거래 타입에 해당하는 ExpenseModel 목록을 filteredTransactions()로 구함
- 그 안의 amount(거래 금액)를 모두 더함
- 총합(Int) 으로 반환
🎯 언제 쓰나요?
- "이번 달 지출 총합은 얼마야?"
- "작년 12월 수입의 총합을 계산해줘!"
- "일주일 간의 지출 합계가 궁금해"
처럼 날짜/타입 조건에 맞는 누적 금액이 필요할 때 사용합니다.
🧮 reduce의 구조
array.reduce(initialValue) { (accumulatedResult, currentElement) in
return 새로운 누적 값
}
- initialValue: 시작값 (여기선 0)
- accumulatedResult: 누적 중간값 ($0)
- currentElement: 현재 순회 중인 항목 ($1)
👇 비교 예시: for문 버전
var total = 0
for item in filtered {
total += item.amount
}
return total
👆 동일한 역할을 하는 한 줄짜리 코드
return filtered.reduce(0) { $0 + $1.amount }
- $0: 누적된 금액 (처음에는 0)
- $1: 현재 순회 중인 ExpenseModel 객체
- $1.amount: 현재 항목의 금액
💬 따라서 "모든 항목의 amount 값을 차곡차곡 더해서 반환해줘" 라는 뜻입니다.
✅ 실제 사용 예
let totalExpense = totalAmount(type: .expense, in: Date(), granularity: .month)
// 👉 이번 달의 지출 총합을 계산
let totalIncome = totalAmount(type: .income, in: someDate, granularity: .year)
// 👉 특정 연도의 수입 총합 계산728x90
LIST