[iOS] reduce(_:_:) vs. reduce(into:_:)

Eugenie·2022년 8월 17일
0

Apple Documentation 에서는
reduce(_:_:)reduce(into:_:) 에 대해 다음과 같이 정의되어 있다.

Returns the result of combining the elements of the sequence 
using the given closure.

주어진 클로저를 이용해 수열의 요소들을 조합한 결과를 반환한다는 의미이다.

reduce(_:_:)

func reduce<Result>(
    _ initialResult: Result,
    _ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result

Return Value

최종 누적값을 리턴한다.
요소가 없다면 결과는 초기값(initialResult) 이다.

initialResult

초기 누적값으로 사용할 값이다.
클로저가 처음 실행될 때 nextPartialResult 에 전달된다.

nextPartialResult

nextPartialResult 클로저의 다음 호출에 사용되거나
반환될 누적값과 요소를 새로운 누적값으로 결합하는 클로저이다.

reduce(into:_:)

func reduce<Result>(
    into initialResult: Result,
    _ updateAccumulatingResult: (inout Result, Self.Element) throws -> ()
) rethrows -> Result

Return Value

최종 누적값을 리턴한다.
요소가 없다면 결과는 초기값(initialResult) 이다.

initialResult

초기 누적값으로 사용할 값이다.

updateAccumulatingResult

요소로 누적값을 업데이트하는 클로저이다.

So what's the difference?

각 메소드의 정의를 살펴보면 알 수 있다.
reduce(_:_:)nextPartialResult 와는 달리
reduce(into:_:)updateAccumulatingResult
inout 키워드가 붙은 Result 를 받고 있다.

바로 이 inout 이 핵심이다.

초기값으로 넘기는 인자 값을 변형하여 최종 결과를 얻고 싶다면 reduce(into:_:) 를 사용하면 된다.


📚 Reference
reduce(::)
reduce(into:_:)
reduce(::) vs reduce(into::)
reduce(::) vs reduce(into::)

profile
🌱 iOS developer

0개의 댓글