- Extension은 기존 클래스, 구조, 열거, 프로토콜 타입에 새로운 기능을 추가할 때 사용
- 원본 소스 코드에 액세스할 수 없는 타입을 확장하는 기능 포함
Extensions in Swift can:
- Add computed instance properties and computed type properties
- Define instance methods and type methods
- Provide new initializers
- Define subscripts
- Define and use new nested types
- Make an existing type conform to a protocol
Extension은 타입에 새 기능을 추가할 수 있지만 기존 기능을 재정의할 수는 없음.
Extension Syntax
extension SomeType {
// new functionality to add to SomeType goes here
}
- 하나 이상의 프로토콜을 채택하여 기존 타입을 확장할 수 있음
- 적합성을 추가하는 방식은 기존 방식과 동일
extension SomeType: SomeProtocol, AnotherProtocol {
// implementation of protocol requirements goes here
}
기존 타입에 새로운 기능을 추가하기 위해 확장을 정의한다면 새로운 기능은 확장이 정의되기 전에 생성되었어도 기존에 인스턴스에서 사용 가능****
Computed Properties