George WS George WS - 19 days ago 10
Swift Question

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

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
?

(I'm essentially looking for something analogous to
friend
in C++.)




Motivation:

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.

Answer

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?

No. The rules you get are the rules you get. There is not some magic way to break them. You can put the two types in the same file, or (at the other extreme) you can move them both off into a module of their own and give them internal scope so that they can see each other but no one else can see them.

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

I don't see why you need this. It is easy to move UIViewControllerAnimatedTransitioning material into a file of its own already. There is no need for exposure of private subviews. That is why this stuff has been broken off into a separate protocol. The roles of animator and view controller are already completely independent. If you think exposure of private subviews is required, you're doing something wrong (and you should be asking a question about that). [For example, it may be that you are unaware of the transitionCoordinator function, which allows a view controller to participate in its transition animation without knowing what it is.]

Comments