Edit: Found a simple way to hide it. At least from the xcode quick help information: Just put the adoption and implementation in an extension of you class and it will not show up there.
Original Answer:
I came up with this example, inspired by inner classes in Java. Here MyVC
does not expose that it implements UICollectionViewDelegate
for internal purposes, while the delegate implementation has access to MyVC
's private variables.
public class MyVC: UIViewController {
private let a = 4 as Int
private var hiddenDelegate: HiddenDelegateImpl?
public override func viewDidLoad() {
super.viewDidLoad()
hiddenDelegate = HiddenDelegateImpl(outer: self)
innerCollectionView.delegate = hiddenDelegate
}
}
private class HiddenDelegateImpl: NSObject, UICollectionViewDelegate {
private weak var outer: MyVC?
init(outer: MyVC) {
self.outer = outer
super.init()
}
private func doStuff() -> Int {
// can access private variables of outer class
return outer?.a
}
// implement delegate methods here
}
Note that HiddenDelegateImpl
could also be an inner class of MyVC, I chose to put it outside for readability.
In contrast to Java instances of inner classes need an instance of the outer class to exists. Since this is not the case with Swift we need to have the outer
workaround.
There is also this nice example which focuses on delegate implementation.
Edit: Made the delegate an instance variable in the outer class to retain it and the reference to the outer class weak to avoid retain cycles.