Can I set default access to private for a class - with explicit overrides for things that I want public?

I can see how to make a class open by default, with the option to make methods more private.
It would be nice (for managing encapsulation) to do the reverse

Something like

class MyClass {
   var thisPropertyIsPrivate:String
   public var thisPropertyIsPublic:Int

   func thisMethodIsPrivate() -> void {}
   public func thisMethodIsPublic() -> void {}

Is there anything like this that I'm missing?

Not for the main body of a class (or struct or enum), but yes for extensions. The access level of a type itself is an upper bound on that of its members, whereas the access level an extension is a default applied to anything inside which doesn’t specify an access level:

public struct Foo {
  private var x: Int = 0

private extension Foo {
  func bar() { print("bar is private") }
  public func baz() { print("baz is public") }

Edit: or at least, that’s how I thought it worked. When I just tried it in a playground, bar is visible outside of Foo, and baz raises a warning “'public' modifier conflicts with extension's default access of 'private'”.

1 Like

@Nevin - yup, I get the same errors (although the compiler seems willing to do what is asked)

this doesn't work for properties though (can't be in an extension), so this enforces a style that separates methods from their associated private properties (as well as requiring them to be explicitly annotated)

No, there is no such feature in Swift.