[Pitch] New access control for access inside type from other files

Apologies in advance if such a thing had already been proposed.

Sometimes, when constructing types, we separate some functionality and encapsulate it within different extensions (Delegate conformance, specific context responsibility etc.).
We often prefer also separating this functionality into separate files for better readability.

This works well until we need to access a property we want to "hide" from the outside world to express it shouldn't be accessed directly.
We can use private or fileprivate, but then we lose the ability to access it from a different file.

What I propose is a new keyword which makes properties and functions marked with it accessible only within this type.

For example:

MyType.swift

class MyType {
    member var myString: String = ""
    ....
}

And then, in a separate file:
MyType+Delegate.swift

extension MyType: MyDelegate {
    func foo() {
        myString = "bar"
    }
}

Trying to access myString from outside the type causes a compilation error.

Of course, the keyword member is just a suggestion, and can be changed.
Other options: context, domain, typemember.

This is my first proposal, so I hope it's detailed sufficiently. I'd appreciate any input you may have.

4 Likes

After giving it some more thought, I believe a better name for this would be ‘typeprivate’, which keeps it more consistent with the current ‘fileprivate’.

Using type is inaccurate because if we get this, it needs to apply to protocols as well.

protected is the standard. It was apparently in the works for C# 8 interfaces (what they call protocols), for example, but as far as I know, it didn't happen.

I believe, that’s very unlikely to ever happen because access scopes in Swift are purely lexical by design. I think the same problem is much better solved by access-controlled protocol conformances.

1 Like

There are 80+ results on these forums, reflecting more than five years of prior discussion, on this topic when one searches for “protected access”:

https://forums.swift.org/search?context=topic&context_id=54051&q=protected%20access&skip_context=true

Not sure there’s much left to say which hasn’t already been said, but by all means if there’s some new insight that’s been overlooked then do share it here!

4 Likes

This is a very frequently made suggestion, e.g. the latest example.

The frequency of this feature request suggests there's some room for improvement, at least for those of us who are from "everything must be private by default" school of thought.

2 Likes

I'd also encourage one to look at the past threads. Maybe also summarize what was debated and see if they have new things to put on the table. It tends to get eyes rolling when the discussion starts rehashing old stuff.

Cool suggestion :+1::+1::+1:

I think the new keyword name can be extentionprivate like fileprivate :grin: