属性必须声明为公共,因为它符合公共协议中的要求?

ero*_*ppa 6 swift

public protocol CDViewModel: class {
    var cancellableList: [AnyCancellable] { get set }
}
public extension CDViewModel {
   func subscribe(_ callback: @escaping (Project) -> Void) {
    cancellableList.append( /*...*/)
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个将在模块外部使用的协议。所以我必须宣布它是公开的。

但我希望符合该标准的类实现具有私有访问权限的 cancelableList。

   class MyClass: CDViewModel {
        private var cancellableList: [AnyCancellable] = [AnyCancellable]()
    }
Run Code Online (Sandbox Code Playgroud)

属性“cancellableList”必须声明为公共,因为它符合公共协议“CDViewModel”中的要求

这可能吗?

eli*_*ght 1

解决此问题的一种方法是创建一个中间对象类,该类可以使用fileprivate. 您在实例中声明“包装对象类型” MyClass,从而符合 的MyClass所需接口。

现在,您可以从协议扩展内部完全访问包装对象 ( wrappedList) 属性,但不能从模块外部访问。

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(/****/)
  }
}
Run Code Online (Sandbox Code Playgroud)

MyClass.swift

class MyClass: CDViewModelProtocol {
    let wrappedList = CDViewModelList()

    func doStuff () {
        self.subscribe(24)
        self.wrappedList.cancellableList // 'cancellableList' is inaccessible due to 'fileprivate' protection level
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢您提出的问题,它让我在这里很好地阅读:

全额信用