[swift-evolution] Idea: Public Access Modifier Respected in Type Definition

James Valaitis jamesvalaitis at me.com
Thu Sep 28 11:17:37 CDT 2017


When declaring a public class or struct the properties still default to internal.
```
public final class NewType {
	/// This property defaults to internal.
	var property: Any?
}
```

This is not the same for a public extension on the type, where then the access modifier is respected for any function or calculated property within the extension.
```
public extension NewType {
	/// This function inherits the public modifier.
	func function() {
	}
}
```

I dislike this inconsistency, and I frequently find that when using my dynamic frameworks my code will not compile, and it will be due to my accidentally writing a public struct but not declaring the properties public.

I believe in the idea that explicitly stating the access modifier leads to more legible code, but in my opinion it can be overdone, and I much prefer to explicitly state my intentions in the modifier on the definition or extension. For example:

```
public struct Coordinate {
	/// Should default to public.
	let latitude: Double
	/// Should default to public.
	let longitude: Double
	/// Should default to public
	init?(latitude: Double, longitude: Double) {
		guard validate(latitude: latitude, longitude: longitude) else { return nil }
		…
	}
}
internal extension Coordinate {
	/// Convenience initialiser to me used internally within the module.
	init(coordinate: CLLocationCoordinate2D) {
		…
	}
}
private extension Coordinate {
	/// Private validation of the coordinate.
	func validate(latitude: Double, longitude: Double) -> Bool {
		…
	}
}
```

This is legible and intuitive. The current behaviour is not.



More information about the swift-evolution mailing list