์ค๋์ ์์
์ค ๋ด๊ฐ ๋ชจ๋ฅด๋ ์ฝ๋๋ฅผ ๋ฐ๊ฒฌํด์ ๊ธ์ ์จ๋ณธ๋ค. reduce! reduce(::)
ํํ๋ง ๋ด์์๋๋ฐ reduce(into::)
ํํ๋ ์๋๋ผ! ์์๋ณด์.
reduce(::)
Returns the result of combining the elements of the sequence using the given closure. ์ฃผ์ด์ง ํด๋ก์ ๋ฅผ ์ฌ์ฉํ์ฌ ์ํ์ค์ ์์๋ฅผ ์กฐํฉํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํฉ๋๋ค.
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
- intialResult
- ์ด๊ธฐ๊ฐ์ด๋ค. ์์ด์์ ์ฒซ์งธํญ์ด๋ผ๊ณ ์๊ฐํ๋ฉด ๋๊ฒ ๋ค.
- nextPartialResult
- ์ด์ ์ ๊ฒฐ๊ณผ๊ฐ, ๊ทธ๋ฆฌ๊ณ Sequence์์ ๋ค์ ๊ฐ์ input์ผ๋ก ๊ฐ๋ ํด๋ก์ ๋ฅผ ์์ฑํ๋ ๊ณณ์ด๋ค.
์์
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
- ์ฒ์์๋ x์ 0์ด ๋ค์ด์ค๊ณ , y์ 1์ด ๋ค์ด์จ๋ค.
- ๋ค์์๋ ๋ํ ๊ฒฐ๊ณผ์ธ x์ 1์ด ๋ค์ด์ค๊ณ y์๋ 2๊ฐ ๋ค์ด์จ๋ค.
- ์ด์ ๊ฐ์ ๋ฐฉ์์ผ๋ก sequence์ ๋๊น์ง ๋ฌ๋ฆฐ๋ค.
- ๋น์ฐํ๊ฒ๋ ์๊ฐ๋ณต์ก๋๋
O(n)
์ด๋ค.
reduce(into:_:)
This method is preferred over reduce(::) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary. ๊ฒฐ๊ณผ๊ฐ copy-on-write์ธ, ์ฆ Array, Dictionary์ ๊ฐ์ ๋ ์, ์น๊ตฌ๋ค์ผ ๋ ์ข์ ๋ฉ์๋!
func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) rethrows -> Result
- initialResult
- ์ด๊ธฐ๊ฐ
- updateAccumulatingResult
- sequence์ ์์๋ฅผ ๊ฐ์ง๊ณ ๊ฐ์ ์ ๋ฐ์ดํธํ๋ ํด๋ก์
- ํต์ฌ์
inout
!!!
์ฌ๊ธฐ์ ์์ reduce(_:_:)
์ reduce(into:_:)
์ ์ฐจ์ด์ ์ด ๋ณด์ธ๋ค. ํ์์ ๊ฒฝ์ฐ ํด๋ก์ ๋ณ์๋ก inout
ํค์๋๊ฐ ๋ถ์ด์๋ ์ ๋ณด๊ฐ ๋ค์ด์จ๋ค. ๋ฌด์จ ์ฐจ์ด์ผ๊น?
inout ํค์๋๊ฐ ์ด๋ ต๋ค๋ฉด, ํด๋น ํฌ์คํ ์ ์ฝ๊ณ ์ค์. ๊ฐ๋จํ๊ฒ ์๊ธฐํ๋ฉด, ์ผ๋จ ๊ธฐ๋ณธ์ ์ผ๋ก closure์ ์ธ์๋ก ๋ค์ด๊ฐ ๋ณ์๋ copy๋๋ค. ๋ฐ๋ผ์ closure ๋ด๋ถ์์ ๊ฐ์ ๋ณ๊ฒฝํ๋๋ผ๋, ํด๋น ํด๋ก์ ์ธ๋ถ์ ๋ณ์๋ ๋ณํจ์ด ์๋ค. (Immutable)
ํ์ง๋ง inout
ํค์๋๋ฅผ ์ฌ์ฉํ ๊ฒฝ์ฐ, ์ธ๋ถ์์ ๋ฃ์ด์ค ๋ณ์ ์ฃผ์ ๊ทธ๋๋ก ๋ฐ์ํ๊ธฐ ๋๋ฌธ์, ํจ์ ๋ด๋ถ์์ ๊ฐ์ ์กฐ์ํ์ ๊ฒฝ์ฐ, ํด๋น ๊ฒฐ๊ณผ๊ฐ ๊ทธ๋๋ก ๋จ์์๋ค. (Mutable)
๊ทธ๋ ๋ค๋ฉด ์ด๋ค ๊ฒฝ์ฐ๋ฅผ ์๊ฐํ๊ณ ๋ง๋ ๊ฒ์ด๋! ๋ฐ๋ก ์ด๊ธฐ๊ฐ์ด ๋ฐฐ์ด, ๋์ ๋๋ฆฌ๋ก ๋ค์ด์จ ๊ฒฝ์ฐ, ํด๋น ๋ฐฐ์ด์์ฒด์ ๊ฐ์ ๋ณ๊ฒฝํด์ฃผ๊ณ ์ถ์ ๋ ์ฌ์ฉํ๋ค. ๋ง์ด ์ด๋ ต๋ค. ์๋ก ์์๋ณด์!
์์
let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
counts[letter, default: 0] += 1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]
์ด ์์ ๋, ํน์ ๋ฌธ์์ด ์์์ ๊ฐ์๋ฅผ ํ์
ํ๊ธฐ ์ํ ์ฝ๋์ด๋ค. ์ด๊ธฐ๊ฐ์ด dictionary๋ก ๋ค์ด๊ฐ๊ณ , ํด๋น ์ด๊ธฐ๊ฐ ์์ฒด๋ฅผ ์ง์ ์ ์ผ๋ก ๋ณ๊ฒฝํ ๊ฒฐ๊ณผ๋ฅผ ์ป๊ณ ์ถ์ดํ๋ค. ๋ง์ฝ ์ด ์ํฉ์์ reduce(into:_:)
๋ฅผ ์ฌ์ฉํ์ง ์์๋ค๋ฉด ์ด๋จ๊น? For ๋ฌธ์ ๋๋ , ForEach๋ก ๋๋ ๊ฒฐ๊ตญ ๋์์ ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ์ผ๋ก ํ์ ๊ฒ์ด๋ค.
์ ๋ฆฌ
ํต์ฌ์ inout
์ด๋ค! ์ด๊ธฐ๊ฐ์ผ๋ก ๋๊ธฐ๋ ์ธ์์์ฒด์ ๋ฌด์ธ๊ฐ ๋ณํ์ ๊ฐํ ์ ์๋๋ก ํ์ฌ ์ต์ข
๊ฒฐ๊ณผ๋ฅผ ์ป๊ณ ์ถ๋ค๋ฉด reduce(into:_:)
๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค. ํนํ ๊ทธ ์ด๊ธฐ๊ฐ์ด ๋์
๋๋ฆฌ, ๋ฐฐ์ด์ธ ๊ฒฝ์ฐ๊ฐ ์ ์ฉํ๊ฒ ๋ค. ์๋ฌด๋๋ ํน์ ๊ฐ์ธ ๊ฒฝ์ฐ๋ ํด๋ก์ ๊ฐ ๊ธฐ๋ณธ์ ์ผ๋ก ์์ํจ์์ด๊ธฐ ๋๋ฌธ์ ์ฌ์ฉํ ์ผ์ด ์์ผ๋๊น.