[swift-evolution] [swift-evolution-announce] [Review] SE-0025 Scoped Access Level

Brent Royal-Gordon brent at architechies.com
Fri Mar 4 21:14:55 CST 2016

> A very important property of the proposal is that anything declared "scoped" is completely sealed inside its scope and cannot be accessed from the outside. This means that the scope can be moved anywhere in the file without the danger of introducing access to implementation details. 
> Allowing a containing scope to see "scoped" in its inner scope would mean that someone could just wrap a scope in another scope to gain access to implementation details without changing anything in the scope itself. The whole point of the proposal is to protect against something like this and make sure that implementation details remain hidden from anything outside the scope.

Wrap it how? You can't introduce arbitrary scopes inside file scope; that is, this is already illegal*:

	do {
		extension SomeType {
			scoped func secret() { ... }

		func intruder(some: SomeType) {

Introducing a scope would require you to declare or extend a type. Thus, moving something into a containing scope in order to allow you to "see" into it would also, by necessity, move the type itself, forcing you to change any code that uses the type. It would be far easier for someone trying to get access to internal details to simply change `scoped` to `private`.

When considering the `scoped` proposal, you must remember that `scoped`'s protections are paper-thin. You are already in the very file which declares the member `scoped`; if you want to deliberately violate that protection, all you must do is change that to `private`.

To the extent there is value in `scoped`, it is because it prevents *mistakes*, not *malice*. So when we're thinking about what `scoped` should do, we should ask, "What is likely to be a mistake?"

I submit that, if you nest one declaration inside another, and the outer declaration accesses implementation details of the inner declaration, that is not likely to be a mistake. If it would be, you can always put the inner declaration into its own extension; then any code which accesses its implementation details will have to be deliberately put in that particular extension.

This does not permanently wall off those implementation details from anything outside the type, but there is *nothing* we can do that will do that, because you are already in the file and can always change the the `scoped` to `private`. 

* The REPL won't show this behavior because it allows arbitrary statements at the top scope; you'll have to try it in a .swift file.

Brent Royal-Gordon

More information about the swift-evolution mailing list