I was wondering if I could do a hidden adoption of a protocol in swift.
In Objective-C, I would use a private header in the m.-file to hide protocols that I don't want to be exposed to the outside. Is something like that possible in swift? Putting a "private" before the protocol does not work, apparently :)
Yes this is exactly the use case. A workaround is to have a function accept all the properties which were private inside the Protocol, and have a protocol extension implement the function.
Swift 4 allows multiple protocols to be called at once with the help of protocol composition.
Protocols allow you to group similar methods, functions, and properties. Swift lets you specify these interface guarantees on class , struct , and enum types. Only class types can use base classes and inheritance from a protocol.
You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With