1oo7
(J. Shad.)
1
Question: when would you ever need to explicitly declare something as internal in Swift?
Seems like internal is always the default. So, under what conditions would you need to make it explicit?
One scenario I can think of from the top of my head is when working with public properties. Suppose you wanted to declare a public property, but want to disallow anyone outside the module (but not the containing file) from calling its setter. In that scenario, you would have to use internal. For example:
public internal(set) var value: Int
Some people also like to use it in scenarios like:
public struct A {
internal struct B {}
}
to make it clear that B is internal otherwise someone not familiar with the access control rules might assume its public (since its nested inside a public struct, I can see why a reasonable person might think that!). It's really a stylistic choice though in my opinion.
4 Likes
Also, you can specify the default access control level for all members in an extension and then override that.
public extension MyType {
// This one's public
func myPublicMethod() {}
// This one's explicitly internal
internal func myInternalMethod() {}
}
6 Likes