Old_SWIFT(221012)/함수이야기

<Reduce>함수 더하기 추론(조금...)

KataRN 2021. 11. 12. 16:45
반응형

안녕하세요. KataRN입니다.

 

오늘은 Reduce 함수에 대해 알아보겠습니다.(이번엔 추론도 더해서 알아보겠습니다.)

 

reduce 번역하면 "줄이다, 감소하다" 입니다.

하지만 이 함수는 덧셈 함수라고 할 수 있습니다.

 

우선 애플 공식문서를 봅시다.

reduce(_:_:)

Applies a closure that collects each element of a stream and publishes a final result upon completion.

Declaration

func reduce<T>(_ initialResult: T, _ nextPartialResult: @escaping (T, Self.Output) -> T) -> Publishers.Reduce<Self, T>

Return Value

A publisher that applies the closure to all received elements and produces an accumulated value when the upstream publisher finishes. If reduce(_:_:) receives an error from the upstream publisher, the operator delivers it to the downstream subscriber, the publisher terminates and publishes no value.

Parameters

initialResult

The value that the closure receives the first time it’s called.

nextPartialResult

A closure that produces a new value by taking the previously-accumulated value and the next element it receives from the upstream publisher.

Discussion

Use reduce(_:_:) to collect a stream of elements and produce an accumulated value based on a closure you provide.

In the following example, the reduce(_:_:) operator collects all the integer values it receives from its upstream publisher:

let numbers = (0...10)
cancellable = numbers.publisher
    .reduce(0, { accum, next in accum + next })
    .sink { print("\($0)") }

// Prints: "55"

 

이번 애플 공식 예제는 조금 헷갈리네요.

제 수준에 맞춰서 바꿔보겠습니다.

let arr = (0...10)
let sum = arr.reduce(0, { (s1: Int, s2: Int) -> Int in
    return s1 + s2
})
print(sum)
//55

 어떻습니까? 쉽죠?

이걸 추론으로 코드를 줄여보겠습니다.

array.reduce(0) { (s1: Int, s2: Int) -> Int in
    return s1 + s2
}

에이~ 한번더 가능?

오케이!

array.reduce(0) { (s1, s2) in s1 + s2 }

오호? 한번더 가능?

오케이!

array.reduce(0) { $0 + $1 }

한번더는 안되겠죠?

쌉가능~

array.reduce( 0, + )

처음꺼랑 비교해보세요ㅋㅋㅋㅋㅋ

이걸 처음 보는사람이 무슨 수로 알겠습니까...(고수제외)

저는 모르겠더라구요.. 근데 이게 너무 편하고 너무 간결해요

클로져와 추론을 이용해서 간추린게...

대신 for문으로 돌린거보다 시간이 더걸립니다.

 

자 그럼 응용한번 해보도록 하죠 이번엔 String으로 문자열을 합쳐보겠습니다.

let arr = (0...10)

let sum = arr.map{String($0)}.reduce("",+)
print(sum)
//012345678910

let sum2 = arr.map{$0}.reduce(""){String($0)+String($1)}
print(sum2)
//012345678910

눈치 빠르신 분들은 벌써 어떻게 쓰면 될지 보이시죠?

여기까진 프로그래머스 기준 레벨1까진 통합니다.

문제는 레벨2로 넘어가면 효율성에서 시간초과가 됩니다.

그러니 적절하게 섞어 쓰는것을 추천드립니다.

 

오늘도 긴글 읽어주셔서 감사합니다.iosKataRNmapSWiFT배열추론코딩테스트코테프로그래머스

 

 

반응형