[swift] 43. reduce

RudinP·2023년 10월 6일
0

Study

목록 보기
62/227

reduce

  • 고차함수
  • 축적
  1. .reduce(초기값) { 축적의 결과가 될 변수(sum), 반복 대상 in
    return ~
    }
struct Friend: Hashable {
	var name: String
    var age: Int
}
let myFriends = [
	Friend(name: "철수", age: 10),
    Friend(name: "철수2", age: 20),
    Friend(name: "철수3", age: 30),
    Friend(name: "철수4", age: 40),
    Friend(name: "철수5", age: 50)
]
let totalAge = myFriends.reduce(0) { partialResult, aFriend in
	return partialResult + aFriend.age
//0(초기값) + 10 + 20 + 30 + 40 + 50
}
  1. .reduce(into: [:]) {
    partialResult, 그룹핑 대상 in
    code
    }
  • code에서 적힌 기준을 기반으로 그룹핑 대상이 묶인다.
  • into: 뒤에는 결과 변수형
let groupedFriends = myFriends.reduce(into: [:]) {partialResult, aFriend in
	partialResult[aFriend.age] = myFriends.filter{ $0.age == aFriend.age}
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글