- reduce는 사실 결합(Combine)이라고 불러야할 기능이다. reduce는 컨테이너 내부의 콘텐츠를 하나로 합치는 기능을 실행하는 고차함수이다.
func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result
func reduce<Result>(
into initialResult: Result,
_ updateAccumulatingResult: (inout Result, Element) throws -> ()
) rethrows -> Result
- initialResult
- The value to use as the initial accumulation value. initialResult is passed to nextPartial Result the first time the closure is executed.
- nextPartialResult
- A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller.
- 초깃값 또는 이전 클로저의 결과값
- into initialResult
- The value to use as the initial accumulating value.
- 즉 inout 키워드를 활용하여 초기값 주소의 직접 값을 대입하겠다는 소리?
- updateAccumulatingResult
- A closure that updates the accumulating value with an element of the sequence.
- The final accumulated value. If the sequence has no elements, the result is
initialResult
.
let numbers = [2,5,6]
let letters = "abracadabra"
// reduce(_:, _:) 형태
// 1
numbers.reduce(0) { particalResult, next in
return particalResult + next
}
// 1 or
numbers.reduce(0,{ (result: Int, next: Int) -> Int in
return result + next
})
// 2
numbers.reduce(0) { $0 + $1 }
// 3
numbers.reduce(0, +)
// 4 ( 문자 a 갯수 구하기)
letters.reduce(0) { (result: Int, next: String.Element) -> Int in
var check = 0
if next == "a" { check += 1}
return result + check
}
// reduce(into:, _:) 형태
// 1
numbers.reduce(into: 0) { result, next in
return result += next
}
// 2
letters.reduce(into: 0) { count, value in
if value == "a" {count += 1}
}
// 3
letters.reduce(into: [:]) { count, value in
count[value, defalut: 0] += 1
}
// 2의 filter를 활용한 개선
letters.filter { $0 == "a"}.count
- reduce(_:, _:) 형태는 값 복사 타입이기 때문에 내부에서 초기값 이자 반환값을 직접 처리를 못한다. 그러므로 4번 같이 result를 함수 내부에서 직접 변경할 수 없으니 따로 변수를 선언해서 return 값의 데이터를 대입한다.
- reduce(into: _:) 형태는 inout 키워드 활용으로 초기값 또는 반환값을 직접 처리할 수 있다. 그러므로 2, 3번처럼 초기값을 빈 dictionary 형태로 선언 후 각 각의 값을 대입해서 활용할 수도 있다.
- #Swift/Higher-Oder-Function/reduce