Friend classes in Swift(访问内部 class 的私有成员)

Friend classes in Swift (access private members of internal class)

我在两个不同的文件中有两个 Swift class,它们都在同一个目标中。有没有一种方法可以让一个人访问另一个人的 private 成员,而不会将他们暴露为 internalpublic

(我本质上是在寻找类似于 C++ 中的 friend 的东西。)


动机:

这对于在单独的 "transition" class 中实现 UIViewControllerAnimatedTransitioning 之类的东西很有用——通常需要对源视图控制器和目标视图控制器有深入的了解——而不需要那些视图控制器将 private 个子视图暴露给目标的其余部分。

I have two Swift classes in two different files, both in the same target. Is there a way to give one access to the private members of the other without exposing them as internal or public?

没有。你得到的规则就是你得到的规则。没有什么神奇的方法可以打破它们。您可以将这两种类型放在同一个文件中,或者(在另一个极端)您可以将它们移到它们自己的模块中并给它们 internal 作用域,这样它们就可以看到彼此,但看不到其他人可以看到它们。

This could be useful for something like implementing UIViewControllerAnimatedTransitioning in a separate "transition" class—typically requiring intimate knowledge of the source and destination view controllers—without requiring those view controllers to expose private subviews to the rest of the target

我不明白你为什么需要这个。很容易将 UIViewControllerAnimatedTransitioning material 移动到它自己的文件中。不需要公开私有子视图。这就是 为什么 这个东西被分解成一个单独的协议。动画师和视图控制器的角色已经完全独立。如果您认为需要公开私有子视图,那您就做错了(您应该问一个关于 that 的问题)。 [例如,您可能不知道 transitionCoordinator 函数,它允许视图控制器在不知道它是什么的情况下参与其过渡动画。]