앱/Swift
Swift) rethrows란
진ddang
2023. 8. 28. 15:13
rethrows란 함수를 파라미터로 받는 함수에서 에러가 발생할수 있음을 의미하는 키워드이다.
즉 최소 한개 이상의 에러를 throw하는 함수를 매개변수로 받아야 한다.
간단한 예제는 다음과 같다.
enum Errors: Error { case someError } func throwErrors(about value: Int) throws -> Int { if value == 0 { throw Errors.someError } return value } func checkThrow(completion: (Int) -> Int ) { do { try throwErrors(about: 0) } catch (let error) { print(error.localizedDescription) } } checkThrow(completion: throwErrors)
이렇게 컴파일 에러가 발생한다.
하지만 여기에서
enum Errors: Error { case someError } func throwErrors(about value: Int) throws -> Int { if value == 0 { throw Errors.someError } return value } func checkThrow(completion: (Int) throws -> Int ) rethrows { do { try throwErrors(about: 0) } catch (let error) { print(error.localizedDescription) } } do { try checkThrow(completion: throwErrors) } catch(let error) { print(error.localizedDescription) }
이러한 코드는 작성이 가능하게 된다.
반응형