how public properties within internal class or struct are accessible while the class or struct itself remains accessible only within the same module.

Generated on 8/7/2024

1 search

In Swift, you can have public properties within an internal class or struct, making the properties accessible from any module while the class or struct itself remains accessible only within the same module. This is achieved through Swift's access control levels.

Here's a brief overview of the relevant access control levels in Swift:

  • public: Accessible from any module.
  • internal: Accessible only within the same module.
  • private: Accessible only within the same file.

When you declare a class or struct as internal (which is the default if no access level is specified), it means that the class or struct can only be accessed within the same module. However, you can still declare its properties as public, making those properties accessible from any module.

For example:

internal class MyClass {
    public var myProperty: String
    internal var anotherProperty: Int

    init(myProperty: String, anotherProperty: Int) {
        self.myProperty = myProperty
        self.anotherProperty = anotherProperty
    }
}

In this example, MyClass is internal, so it can only be accessed within the same module. However, myProperty is public, so it can be accessed from any module, while anotherProperty remains internal.

For more details on access control in Swift, you can refer to the session A Swift Tour: Explore Swift’s features and design from WWDC 2024.