Swift 有访问修饰符吗? [英] Does Swift have access modifiers?

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

问题描述

在 Objective-C 中,实例数据可以是 publicprotectedprivate.例如:

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).

允许在定义模块(目标)之外使用实体.在指定框架的公共接口时,您通常使用 openpublic 访问.

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.

但是,open访问只适用于类和类成员,它与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.内部

使实体能够在定义模块(目标)中使用.在定义应用或框架的内部结构时,您通常使用 internal 访问权限.

// 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 访问来隐藏特定功能的实现细节.

3. fileprivate

Restricts the use of an entity to its defining source file. You typically use fileprivate access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.

// 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.私有

将实体的使用限制在其封闭声明中.当特定功能的实现细节仅在单个声明中使用时,您通常使用私有访问来隐藏这些细节.

// 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天全站免登陆