首页 > 解决方案 > swift库如何隐藏其实现

问题描述

在某个时间点,我们可能会尝试查看苹果为 ios 开发提供的包/库的代码。例如:UIViewController、SFSafariViewController 等。当我们进入这些包/库的文件时,我们会发现类似这样的内容。

extension UIViewController {

    @available(iOS 5.0, *)
    open var children: [UIViewController] { get }

    @available(iOS 5.0, *)
    open func addChild(_ childController: UIViewController)


    @available(iOS 5.0, *)
    open func removeFromParent()

    @available(iOS 5.0, *)
    open func transition(from fromViewController: UIViewController, to toViewController: UIViewController, duration: TimeInterval, options: UIView.AnimationOptions = [], animations: (() -> Void)?, completion: ((Bool) -> Void)? = nil)

    @available(iOS 7.0, *)
    open var childForStatusBarStyle: UIViewController? { get }

    @available(iOS 7.0, *)
    open var childForStatusBarHidden: UIViewController? { get }

}

它只是该文件包含的内容的一部分。但这只是一个方法签名,这些方法在其实现中还有更多内容,对用户访问是隐藏的。

我的问题是

这怎么可能?我们如何隐藏或只提供给用户使用的函数签名,而其余的东西是隐藏在用户眼中的?

标签: iosswift

解决方案


UIKit is a framework so it has Access Control

From docs.swift.org

Access control restricts access to parts of your code from code in other source files and modules. This feature enables you to hide the implementation details of your code, and to specify a preferred interface through which that code can be accessed and used.

You can add framework to your project with Access Control

Access Control document

Swift standard library

In Swift Access Controls from docs.swift.org:

Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use open or public access when specifying the public interface to a framework. The difference between open and public access is described below.

Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.

File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.


推荐阅读