Swift - internally implement public protocol

2019-07-22 09:19发布

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?

0条回答
登录 后发表回答