Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] where Self 사용 방법 (where Element:, where Element ==, where Self) 본문

iOS 응용 (swift)

[iOS - swift] where Self 사용 방법 (where Element:, where Element ==, where Self)

jake-kim 2023. 5. 1. 23:28

구분하기 - protocol의 Where에서 Self: 와 Self ==

extension ProtocolA where Self: ClassA {
}

extension ProtocolB where Self == StructA {
}

protocol 과 where 개념

  • where은 protocol의 extension에서 사용
  • where Self를 사용하는 이유는 protocol를 준수하는 타입 중 특정 타입에만 extension한다는 의미로 사용
extension ProtocolA where Self: ClassA {
}

extension ProtocolB where Self == StructA {
}

콜론과 등호의 차이

ex) 예제에 사용할 protocol, struct, class 준비

protocol ProtocolA {
}

protocol ProtocolB {
}

struct StructA: ProtocolB {
}

class ClassA {
}

class ClassB: ProtocolB {
}
  • 콜론은 클래스 타입만을 대상으로 protocol extension을 제약
    • struct를 사용하면 컴파일 에러가 발생
    • 콜론을 사용하면 서브클래스에도 추가되는 것 - 아래 예제처럼 ClassA를 상속하는 ABC도 printSome()을 사용할 수 있음
// extension ProtocolA where SomeType: ClassType
// ClassA를 상속하고, ProtocolA를 준수하는 모든 타입을 대상
extension ProtocolA where Self: ClassA {
    func printSome() {
        print("some")
    }
}

class ABC: ClassA, ProtocolA {
}

// abc는 printSome() 사용이 가능
let abc = ABC()
abc.printSome()
  • 등호는 해당 프로토콜을 준수하는 타입만을 대상으로함
    • 콜론은 클래스 대상으로만 지정하지만 등호는 해당 프로토콜을 준수하는 모든 타입이 가능
    • 등호와 콜론의 또다른 차이 - 등호는 해당 타입만을 대상(서브클래스들 x), 콜론은 서브클래스들에도 extension 영향 o
// where ProtocolB SomeType == {ProtocolB의 타입 중 하나}
// ProtocolB를 준수하고 있는 타입을 대상
extension ProtocolB where Self == StructA {
}

extension ProtocolB where Self == StructA {
}

extension ProtocolB where Self == ClassB {
    func printSome2() {
        print("some2")
    }
}
  • 등호는 서브클래스 타입에는 적용되지 않고 해당 타입에만 적용되므로, ClassB를 서브클래싱한 ABC2에서 printSome2() 사용 불가

결론

  • where은 protocol의 extension에서 특정 타입에서만 확장하고자 할 때 사용
  • 콜론은 해당 클래스 타입과 서브 클래스들에 영향을 미침
extension ProtocolA where Self: ClassA {
}
  • 등호는 해당 타입만을 대상으로함 (+ 등호 뒤에 나오는 타입은 이미 해당 프로토콜을 준수하고 있어야함)
extension ProtocolB where Self == StructA {
}

 

* 전체 코드: https://github.com/JK0369/ExWhere
* 참고

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols/

Comments