gpt4 book ai didi

swift - 访问级别的指导原则在 swift 中意味着什么

转载 作者:行者123 更新时间:2023-11-28 13:17:03 24 4
gpt4 key购买 nike

swift 访问级别的指导原则是

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.

谁能告诉我一个关于

的代码示例

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.

我不清楚访问级别原则的含义

最佳答案

可访问性级别按升序排列:

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

你不能使用

private class Foo {
}
public var myFoo:Foo

因为 myFoo 在模块外可见,但类 Foo 不可见,因此任何使用 myFoo 的人都不知道如何处理它,它有多大等。如果将 myFoo 更改为私有(private),那么一切都很好,因为任何可以访问 myFoo 的人也可以访问类 Foo。

同样,您不能使用:

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

出于同样的原因,getMyFoo 的调用者不知道(不能)知道 Foo 是什么,因此无法正确处理它。

本质上,如果一个类型是私有(private)的(或非公共(public)的),那么该类型的对象就不可能有任何外部可见性。

关于swift - 访问级别的指导原则在 swift 中意味着什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28612321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com