티스토리 뷰
어떤건 required init에 구현해야하고, 어떤건 super.init에 구현되어야 하는데 이유가 궁금해졌습니다.
required init
먼저 required init은 단어 그대로 '필수적인' init 인데, 사용하는 방법은 여러가지 방법이 있습니다.
하위클래스 required init() 생략
상위클래스를 상속받는 하위 클래스 예시 코드를 먼저 봅시다.
하위클래스(ChildClass)에서 requried init() 메서드 호출이 없어도 자동적으로 상속받는 상위클래스(ParentClass)의 required init을 호출하게 되어 10이 출력됩니다.
하위 클래스 required init() 구현
그럼 하위클래스의 required init() 메서드를 호출하면 어떻게 될까?
- 하위클래스(ChildClass)의 required init() 호출
- 상위클래스(ParentClass)의 required init() 호출
하위클래스에 required init()을 구현하게 되면 하위클래스(ChildClass) 객체 초기화시 상위클래스(ParentClass)의 required init()이 자동으로 호출되기 때문에 super.init()을 작성하지 않아도 됩니다.
super.init()은 이럴때 씁니다.
상위 클래스의 required init()에 파라미터가 있으면 하위클래스의 required init()에 super.init()을 호출해야 합니다.
이해를 돕기 위해 예시를 보죠. (super.init()을 하지않았을 때)
super.init을 호출하라는 컴파일 에러가 납니다.
아래처럼 super.init을 호출해주면
해결!
print 되는 결과를 보면
- Child가 먼저 print되고
- super.init(message) 이 호출됩니다.
즉, 초기화 LifeCycle은 아래와 같습니다.
- 하위 클래스 required init()
- super.init()
- 하위클래스 method, property
정리
그럼 처음 질문으로 돌아가서
어떨때는 required init에 구현되야하고, 어떨때는 super.init() 이후에 구현되어야 하는지 정리를 해보면
하위클래스 required init()에 구현되어야 하는건 상위클래스 초기화 보다 일찍 구현되어야 할때 사용.
super.init() 이후에 구현되어야 하는건 하위클래스의 method, property에 접근할때 사용됩니다.
참고
1. https://sonihemant111.medium.com/required-initializers-in-swift-4805de8ade9e
'iOS' 카테고리의 다른 글
[iOS] Localization - 다국어 지원 (0) | 2023.05.16 |
---|---|
[iOS]긴급심사 요청 (0) | 2023.05.07 |
[iOS] FileManager - 폴더, 파일 생성 & 삭제 (0) | 2023.04.04 |
[iOS] AVAssetWriter로 비디오 저장 (2) | 2023.03.26 |
RxSwift - Reactive Extensions (.rx) (0) | 2023.03.11 |
- Total
- Today
- Yesterday
- swift property
- Swift 내림차순
- 2023년 회고
- swift programmers
- Class
- Swift 알고리즘
- swift (programmers)
- Swift Error Handling
- swift 고차함수
- Swift RIBs
- Swift joined
- Swift inout
- CS 네트워크
- Swift Leetcode
- Swift ModernRIBs
- Swift joined()
- RTCCameraVideoCapturer
- RIBs tutorial
- Combine: Asynchronous Programming with Swift
- 원티드 프리온보딩
- removeLast()
- swift protocol
- ios
- Swift 프로그래머스
- Swift final
- iOS error
- Swift
- swift reduce
- Swift 프로퍼티
- Swift init
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |