Question about the vision for `private`

I know this is a well-worn topic, but I still often bump into the absence of a “typeprivate” scope. For example, we are encouraged to mark state or environment variables private in SwiftUI (and indeed if we don’t then the view struct gets an inappropriate memberwise initializer), but doing so makes it impossible to place functions & computed properties that use those state variables into an extension to the view in a separate file.

It would be so useful to be able to mark a property as accessible only from within the same declaration or in-module extensions to that declaration.

Again, I’m aware this has been talked to near-death. But hope springs eternal.

Objections I’ve seen in the prior extensive threads (beyond bare statements that Swift’s visibility system uses lexical and not type-based scopes) include:

There are at least two reasonable counterarguments.

  • If a file is getting too long to be manageable, it indicates that the type itself is too complex, and should be reconceived. This is likely true in many cases, but not others. For example, to break a SwiftUI subview out into its own View struct often requires a careful dance to pass down the relevant state variables, and it’s unfortunate to have to do that when the subview has complex logic but is semantically part of the main view and dependent on its state.
  • The difficulty in working with a long file comes from tooling problems and should be solved in that domain.

It’s too bad typeprivate has been rejected and is unlikely to be revisited anytime soon.

2 Likes