rethrows에 대해

Young Min Sim ·2021년 12월 24일
0

rethrows란?

public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
어느날 map, reduce, filter 등에 있는 rethrows가 무엇인지 궁금해졌다.
분명 공부한 기억이 있는데 생각이 안나는 걸로 봐선 제대로 안한게 맞는듯.

우선 애플의 정의에 따르면 이렇다.

A function or method can be declared with the rethrows keyword to indicate that it throws an error only if one of it’s function parameters throws an error. These functions and methods are known as rethrowing functions and rethrowing methods. Rethrowing functions and methods must have at least one throwing function parameter.

이를 응용하여 정리하자면

  • rethrows 함수는 throwing function을 파라미터로 가진다
  • throws 함수는 꼭 throwing function을 파라미터로 가질 필요는 없다.

또한 rethrows 함수는

  • 파라미터가 throw인 경우 try가 필요 없고,
  • 파라미터가 throw가 아닌 경우 try가 필요하다.
func ex(f: () throws -> Void) rethrows -> Int {
    f()
    return 0
}

func input() {
    print("called")
}

func input2() throws {
    print("called")
}

ex(f: input) // try 붙일 시, 컴파일러가 경고(No calls to throwing functions occur within 'try' expression)함
try ex(f: input2) 

이는 map, filter 등 유사한 타입을 가지는 고차함수들도 동일하게 동작한다. rethrows에 대한 설명을 찾다 보면 '파라미터로 받은 함수가 오류를 던진다는 것을 알 수 있다'는 식으로 표현 하는데 이 예가 딱 그 예시인 것 같다.

제약조건

  • throw함수는 rethrow함수를 오버라이딩할 수 없다.
  • throw함수는 프로토콜의 rethrow requirements를 충족시킬 수 없다.

이 부분은 throw -> rethrow 이 단방향으로 인한 제약조건이라고 생각하면 될 것 같다.

그래서 언제 쓰는건지?

파라미터로 들어오는 함수로 throw하거나 혹은 throw하지 않는 두 케이스 모두 들어올 때 각각의 케이스에 대해 비슷한 폼을 가지는 함수를 2개(에러처리로 인해 try가 필요한, 에러처리가 필요 없어 try가 불필요한 함수 2개)를 만들지 않고 하나만으로 대응할 수 있다, 정도로 정리할 수 있을 것 같다.

참고자료
https://stackoverflow.com/questions/43305051/what-are-the-differences-between-throws-and-rethrows-in-swift

0개의 댓글