Swift是否具有访问修饰符? [英] Does Swift have access modifiers?

查看:127
本文介绍了Swift是否具有访问修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C实例中,数据可以是公开受保护的私有。例如:

In Objective-C instance data can be public, protected or private. For example:

@interface Foo : NSObject
{
  @public
    int x;
  @protected:
    int y;
  @private:
    int z;
  }
-(int) apple;
-(int) pear;
-(int) banana;
@end

在Swift引用中我没有提到访问修饰符。可以限制Swift中数据的可见性吗?

I haven't found any mention of access modifiers in the Swift reference. Is it possible to limit the visibility of data in Swift?

推荐答案

Swift 3.0.1 开始,共有 4个访问级别 ,以下从最高(最低限制)到最低(最高限制)进行描述。

As of Swift 3.0.1, there are 4 levels of access, described below from the highest (least restrictive) to the lowest (most restrictive).

启用实体使用在定义模块(目标)之外。指定框架的公共接口时,通常使用 open public 访问权限。

Enable an entity to be used outside the defining module (target). You typically use open or public access when specifying the public interface to a framework.

但是, 开放访问权限仅适用于班级和班级成员,并且与 public不同访问方式如下:

However, open access applies only to classes and class members, and it differs from public access as follows:


  • public 类和类成员只能在定义模块(目标)内被子类化和覆盖。

  • open 类和类成员可以被子类化和覆盖在定义模块(目标)之内和之外。

  • public classes and class members can only be subclassed and overridden within the defining module (target).
  • open classes and class members can be subclassed and overridden both within and outside the defining module (target).

// First.framework – A.swift

open class A {}

// First.framework – B.swift

public class B: A {} // ok

// Second.framework – C.swift

import First

internal class C: A {} // ok

// Second.framework – D.swift

import First

internal class D: B {} // error: B cannot be subclassed



2。 内部



启用在定义模块(目标)中使用的实体。在定义应用程序或框架的内部结构时,通常使用内部访问。

// First.framework – A.swift

internal struct A {}

// First.framework – B.swift

A() // ok

// Second.framework – C.swift

import First

A() // error: A is unavailable



3。 fileprivate



限制将实体用于其定义的源文件。当在整个文件中使用特定细节的实现细节时,通常使用 fileprivate 访问权限。

// First.framework – A.swift

internal struct A {

    fileprivate static let x: Int

}

A.x // ok

// First.framework – B.swift

A.x // error: x is not available



4。 private



限制将实体用于其随附的声明。通常,当仅在单个声明中使用这些细节时,通常使用 private 访问权限来隐藏特定功能的实现细节。

4. private

Restricts the use of an entity to its enclosing declaration. You typically use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.

// First.framework – A.swift

internal struct A {

    private static let x: Int

    internal static func doSomethingWithX() {
        x // ok
    }

}

A.x // error: x is unavailable

这篇关于Swift是否具有访问修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆