[Swift] Nested protocol concept (#Swift 5.10)

ganeshrajugalla
2 min readJan 23, 2024

--

nested protocol

  • In versions below swift 5.10, it is not possible to define the protocol under struct/class/enum/actor/function as shown below.
  • If you try to create a delegate protocol in Swift 5.10 or earlier, you must define the delegate externally as shown below, and access it with fullName when accessing it from within.
  • (If the protocol can be defined in TableView, it can be accessed from the outside as TableView.Delegate, and from the inside, it can be accessed simply by the name of Delegate)
class TableView: UIView {
weak var delegate: TableViewDelegate
}

protocol TableViewDelegate {

}
  • From swift 5.10, internal protocol definition is possible.
  • Concise access is possible with TableView.Delegate from the outside and simply Delegate from the inside.
class TableView {
weak var delegate: Delegate?

protocol Delegate { /* ... */ }
}

(who uses it)

  • TableView is also used. The advantage is that it is easy to intuitively understand that it is related to TableView because it is accessed through a namespace.
class DelegateConformer: TableView.Delegate {
func tableView(_: TableView, didSelectRowAtIndex: Int) {
// ...
}
}

reference

--

--