A2oz

What is the difference between internal and public class in Swift?

Published in Swift 2 mins read

The main difference between an internal and a public class in Swift lies in their accessibility:

  • Internal classes can be accessed only within the same module (a group of source files compiled together). They are the default access level for classes in Swift.
  • Public classes can be accessed from any module, including external ones.

Here's a simple analogy: Imagine a company with two departments. The internal department can only be accessed by employees within that department, while the public department can be accessed by anyone, both inside and outside the company.

Practical Implications:

  • Internal classes are ideal for encapsulating logic specific to your app, preventing external frameworks or libraries from accessing or modifying it.
  • Public classes are used when you want to expose functionality to other modules or projects. This allows you to create reusable components or frameworks that can be shared with others.

Example:

Let's say you're building an iOS app with a networking library. You might want to keep the internal logic of your networking library hidden, but expose public functions for making network requests.

  • Internal class: NetworkManager (handles the internal implementation of network requests)
  • Public class: APIService (provides public functions for making network requests)

This way, you control the accessibility of your classes and protect the internal details of your networking library while still providing a clear API for other parts of your app to use.

Related Articles