Notice
Recent Posts
Recent Comments
Link
관리 메뉴

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

[iOS - swift] Protocol 확장에서 프로퍼티 치환 방법, 프로토콜 프로퍼티 이름 중복 해결 (#@_implements) 본문

iOS 응용 (swift)

[iOS - swift] Protocol 확장에서 프로퍼티 치환 방법, 프로토콜 프로퍼티 이름 중복 해결 (#@_implements)

jake-kim 2023. 10. 26. 01:32

Protocol 프로퍼티 치환

  • 일반적으로 protocol에서 프로퍼티를 선언하면, 이 프로토콜을 준수하는 쪽에서 똑같은 프로퍼티 이름으로만 접근이 가능
protocol SomeProtocol {
    var myProperty: Int { get }
}

struct SomeStruct: SomeProtocol {
    var myProperty: Int
}

만약 프로퍼티 이름이 다르면 컴파일 에러 발생)

  • @_implements를 사용하면 다른 이름으로 사용이 가능

@_implements 키워드

  • @_implements(ProtocolName, propertyName)으로 프로퍼티 위에 선언하여 사용
struct SomeStruct2: SomeProtocol {
    @_implements(SomeProtocol, myProperty)
    var myProperty2: Int // ok
}
  • 만약 여러개의 프로토콜을 준수하는데, 프로퍼티 이름이 중복될때도 이 방법을 사용하여 이름 중복 문제를 해결이 가능

ex) 프로토콜 두 개가 존재 (프로퍼티 이름은 같지만 Type이 다른 상태)

protocol SomeProtocol {
    var myProperty: Int { get }
}

protocol OtherProtocol {
    var myProperty: String { get }
}
  • 이 두 프로토콜을 준수하면 이름 중복으로 인해 컴파일 에러 발생

  • @_implements를 사용하면 프로퍼티 이름뿐만이 아닌 프로토콜 분리가 가능하기 때문에 아래처럼 사용이 가능
struct SomeStruct3: SomeProtocol, OtherProtocol {
    @_implements(SomeProtocol, myProperty)
    var p1: Int
    
    @_implements(OtherProtocol, myProperty)
    var p2: String
}

* 참고

https://forums.swift.org/t/swift-should-report-conflicting-requirement-in-child-protocol-as-early-as-possible/50047/2

Comments