Hi,
when declaring variables or constants inside a Struct in SwiftUI projects is it by default private or internal ? seems little confusing cause I see some using the private word explicitly sometimes.
Kindest Regards
It is internal by default.
You can see the difference:
struct ContentView: View {
var topic = "Topic"
var body: some View {
TopicDetailView(topic: topic)
}
}
struct TopicDetailView: View {
var topic: String
var body: some View {
Text("Selected topic \(topic)")
}
}
If you declare private, you'll get compiler error
struct ContentView: View {
var topic = "Topic"
var body: some View {
TopicDetailView(topic: topic) // <<-- Error here: 'TopicDetailView' initializer is inaccessible due to 'private' protection level
// No error if declared internal
}
}
struct TopicDetailView: View {
private var topic: String // <<-- Now private
var body: some View {
Text("Selected topic \(topic)")
}
}
More details here: https://www.appcoda.com/swift-access-levels/
The available access levels in Swift are the following:
- private: This is the most strict access level, as entities marked as private are accessible only inside their defining type (such as properties or methods inside a class or structure), or their defining source file if they’re top-level types (such as classes, structures, enumerations or protocols defined in a file). None of these entities can be accessed by parts of code being outside their defining type or file.
- file-private: This is a less strict access level, as it’s between the private and the internal (see next). Entities marked as file-private are visible and accessible from any other entity only inside the same source file, but not outside of it.
- internal: The internal access level is the default one that is given automatically to all entities that they have not been marked otherwise. It’s actually the access level of all entities by default even though it’s not explicitly written (it’s implied). Internal entities are normally accessible in the scope of their defining module, but inaccessible by parts of code belonging to other modules. We’ll talk about modules later in this post.
- public: The less restrictive access level existing in Swift. By making an entity public you make it accessible by other parts of code inside the same module, and to other modules as well. For example, you have a library integrated into a project as a Swift Package; entities that should be available to the project out of the library must be marked as public, otherwise they won’t be accessible. More about that later.
- open: Similar to public, but it provides an additional “freedom”: Classes and methods marked as open can be subclassed and overridden respectively out of their defining module. More about that later too.