Notice
Recent Posts
Recent Comments
Link
관리 메뉴

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

[iOS - swift] nested protocol 개념 (#Swift 5.10) 본문

iOS 응용 (swift)

[iOS - swift] nested protocol 개념 (#Swift 5.10)

jake-kim 2024. 1. 24. 01:31

nested protocol

  • swift 5.10 아래 버전에서는 아래처럼 protocol을 struct/class/enum/actor/function 하위에 정의가 불가능

  • swift 5.10 이전에서 Delegate protocol을 만들려고하면 아래처럼 외부에 Delegate를 정의하고, 안에서도 접근할때 fullName으로 접근해야함
    • (TableView안에 protocol 정의가 가능하면 외부에서는 TableView.Delegate로 접근이 가능하고, 내부에서는 단순히Delegate 이름으로만 접근이 가능)
class TableView: UIView {
    weak var delegate: TableViewDelegate
}

protocol TableViewDelegate {
}
  • swift 5.10부터는 내부에 protocol정의가 가능
    • 외부에서는 TableView.Delegate, 내부에서는 단순히 Delegate로 간결하게 접근이 가능
class TableView {
  weak var delegate: Delegate?
  
  protocol Delegate { /* ... */ }
}

사용하는쪽)

  • 사용하는쪽도 TableView. 네임스페이스로 접근하기 때문에 직관적으로 TableView와 관련된 것이라는 의미 파악도 쉬운 장점
class DelegateConformer: TableView.Delegate {
  func tableView(_: TableView, didSelectRowAtIndex: Int) {
    // ...
  }
}

* 참고

- https://github.com/apple/swift-evolution/blob/main/proposals/0404-nested-protocols.md

Comments