starcwl
starcwl

Reputation: 406

What is the Guiding Principle of Access Levels meaning in swift

The Guiding Principle of Access Levels of swift is

No entity can be defined in terms of another entity that has a lower (more >restrictive) access level. For example:

A public variable cannot be defined as having an internal or private type, because the type might not be available everywhere that the public variable is used.

A function cannot have a higher access level than its parameter types and return type, because the function could be used in situations where its constituent types are not available to the surrounding code.

could any body show me a code example about

A public variable cannot be defined as having an internal or private type, because the type might not be available everywhere that the public variable is used.

and

A function cannot have a higher access level than its parameter types and return type, because the function could be used in situations where its constituent types are not available to the surrounding code.

I don't know the clearly meaning of the principle of access level

Upvotes: 0

Views: 245

Answers (2)

Aaron Rasmussen
Aaron Rasmussen

Reputation: 13316

Here are some simple examples:

internal protocol InternalProtocol { }

class MyClass {

    // V~~~ This won't work, because InternalProtocol is internal, but the variable is public
    public let myInternalProtocolVariable: InternalProtocol

    // V~~~ This won't work because InternalProtocol is internal, but the function is public
    public func publicFunc(ip: InternalProtocol) -> InternalProtocol {
        return ip
    }
}

The idea is that the caller of the function, or the object accessing the variable has to have access to the types that are used in the function or the variable.

If the user doesn't have access to InternalProtocol - i.e., they can't "see" it - then they shouldn't be able to "see" any variables or functions that use that type either.

Upvotes: 0

David Berry
David Berry

Reputation: 41236

Accessibility levels are, in increasing order:

private - only this file/class
internal - only this module
public - anybody

You can't use

private class Foo {
}
public var myFoo:Foo

because myFoo is visible outside the module but class Foo isn't, therefore anybody using myFoo wouldn't know what to do with it, how big it was, etc. If you change myFoo to private, then it's all good because anybody that has access to myFoo also has access to class Foo.

Likewise, you can't use:

private class Foo {
}
public func getMyFoo() -> Foo {...}

for the same reasons, the caller of getMyFoo doesn't (can't) know what Foo is, so has no way to properly deal with it.

Essentially if a type is private (or not public) then there can't be any external visibility of objects of that type.

Upvotes: 2

Related Questions