Swift의 프로토콜을 보면 Optional Funcion 이라는 것이 있다. 말 그대로 구현해도 되고 구현하지 않아도 되는 함수라는 뜻이다.
protocol Dog {
func bark()
}
extension Dog {
func bark() {
print("Bow-wow")
}
}
final class Samoyed: Dog {
init() {
bark()
}
}
Samoyed()
위 코드를 실행하면 “Bow-wow”를 출력하는 것을 볼 수 있다. 그런데 protocol은 구현체가 아닌데 어떻게 이게 가능할까?
Protocols can be extended to provide method, initializer, subscript, and computed property implementations to conforming types. This allows you to define behavior on protocols themselves, rather than in each type’s individual conformance or in a global function.
결론부터 말하면 스위프트에서 제공하는 Extension 기능이 매우 강력하기 때문이다. Protocol에도 Extension을 사용하면 Protocol 자체에 대한 동작을 정의할 수 있다.
Protocol requirements with default implementations provided by extensions are distinct from optional protocol requirements. Although conforming types don’t have to provide their own implementation of either, requirements with default implementations can be called without optional chaining.
하지만 protocol extension를 사용해 테스트할 수 있는 구조를 짜려면 어려움이 있을 것이다. Extension 된 기능과 protocol을 사용해서 구현된 객체에서 컴파일 타임에 커플링이 생기기 때문. extension으로 구현된 func은 static method dispatch가 되기 때문에 이것을 재정의하기란 매우 어려우므로 테스트를 하려면 protocol을 사용해서 새로운 mock 객체를 생성해서 테스트해야한다. 따라서 사용하는 ViewModel에 비즈니스 로직이 있고 따르는 Protocol이 Extension func을 기본적으로 제공하고 있다면 구현한 ViewModel를 테스트 하기란 어려울 것으로 예상된다. 편리한 기능 같지만 잘 생각해서 사용하는 것이 좋을 것 같다.
참고
Protocols — The Swift Programming Language (Swift 5.6)
Protocols A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of tho
docs.swift.org
'Swift > 학습' 카테고리의 다른 글
Existential any in Swift explained with code examples(번역) (0) | 2023.04.06 |
---|---|
Swift Opaque Types(번역) (0) | 2023.03.28 |
enum으로 특정 단위를 명확하게 표현하기 (0) | 2022.09.25 |
2022 WWDC Embrace Swift Generics (1) | 2022.07.04 |
Swift Subscripts (0) | 2022.05.23 |