Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property must be declared public because it matches a requirement in public protocol?

Tags:

swift

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?

like image 774
erotsppa Avatar asked Mar 10 '20 04:03

erotsppa


Video Answer


1 Answers

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

like image 109
elight Avatar answered Nov 01 '22 05:11

elight