public protocol CDViewModel: class {
var cancellableList: [AnyCancellable] { get set }
}
public extension CDViewModel {
func subscribe(_ callback: @escaping (Project) -> Void) {
cancellableList.append( /*...*/)
}
}
I have a protocol that will be used outside of the module. So I have to declare it public.
But I want the class conforming to that to implement cancellableList with private access.
class MyClass: CDViewModel {
private var cancellableList: [AnyCancellable] = [AnyCancellable]()
}
Property 'cancellableList' must be declared public because it matches a requirement in public protocol 'CDViewModel'
Is this possible?
One workaround to this is to create an intermediate object class that can protect access to its variables using fileprivate
. You declare that 'wrapper object type' in your MyClass
instance thereby conforming to MyClass
's required interface.
Now you have full access to the wrapped object (wrappedList
) properties from within the protocol extension, but not from outside the module.
CDViewModel.swift
import Combine
class CDViewModelList {
fileprivate var cancellableList: [AnyCancellable] = [AnyCancellable]()
}
protocol CDViewModelProtocol: AnyObject {
var wrappedList: CDViewModelList { get }
}
extension CDViewModelProtocol {
func subscribe(_ callback: Int) {
self.wrappedList.cancellableList.append(/****/)
}
}
MyClass.swift
class MyClass: CDViewModelProtocol {
let wrappedList = CDViewModelList()
func doStuff () {
self.subscribe(24)
self.wrappedList.cancellableList // 'cancellableList' is inaccessible due to 'fileprivate' protection level
}
}
Thanks for the question it brought me to a good read here:
FULL CREDIT
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