Swift - internally implement public protocol

别等时光非礼了梦想. 提交于 2019-12-11 04:27:08

问题


Let say I've a protocol that I need to make public. Additionally I've a class that implements this protocol, but in a way that I want to keep internal. So I'd like to do something like:

public protocol CustomDelegate {
  func didLoad()
}

public class Foo {
  public var delegate: CustomDelegate?
  var internalDelegate: CustomDelegate?
  ...
}

public class Bar {
  var foo: Foo
  init() {
    self.foo = Foo()
    self.foo.internalDelegate = self
  }
}
extension Bar: CustomDelegate {
  func didLoad() {
    print("bar has loaded")
  }
}

This doesn't work because Bar's implementation of CustomDelegate is internal, while CustomDelegate is public. However I only care about the extension being used internally, so things should be fine. In other words I'd like the extension to be an internal extension, as would be the case if the class was internal, but Swift is forcing it to be public. One stupid way to make this work is by duplicating the protocol in an internal protocol as:

public protocol CustomDelegate {
  func didLoad()
}
protocol InternalCustomDelegate {
  func didLoad()
}

public class Foo {
  public var delegate: CustomDelegate?
  var internalDelegate: InternalCustomDelegate?
}

public class Bar {
  var foo: Foo
  init() {
    self.foo = Foo()
    self.foo.internalDelegate = self
  }
}
extension Bar: InternalCustomDelegate {
  func didLoad() {
    print("bar has loaded")
  }
}

but this sucks. Is there a better way?

来源:https://stackoverflow.com/questions/39584069/swift-internally-implement-public-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!