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:
-
The current behavior of
private
is essential to be able to know that the implementation details of a type can’t be fiddled with from outside the file. Which is true but does not preclude the utility of a separatetypeprivate
visibility level. -
The arbitrariness of a file scope makes it a useful place to define access control boundary. Again, true but doesn’t address the problem that a single file can get bloated and it would be useful to allow specific members to be designated as accessible from extensions in other in-module files.
-
“[I]f the enclosing type doesn’t quite encompass the code that ought to have access to the declaration, you either need to move declarations into/out of the type to grant/restrict access, or you need to abandon
typeprivate
.” Okay—but it’s extremely common that the enclosing type does encompass the code that ought to have access to the declaration; we just want to split parts of a type’s definition into multiple files.
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.