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

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

我没有发现任何提到的访问修饰符在Swift参考。是否有可能限制Swift中数据的可见性?


当前回答

你可以使用的一个选项是将实例创建包装到一个函数中,并在构造函数中提供适当的getter和setter:

class Counter {
    let inc: () -> Int
    let dec: () -> Int

    init(start: Int) {
        var n = start

        inc = { ++n }
        dec = { --n }
    }
}


let c = Counter(start: 10)

c.inc()  // 11
c.inc()  // 12
c.dec()  // 11

其他回答

你可以使用的一个选项是将实例创建包装到一个函数中,并在构造函数中提供适当的getter和setter:

class Counter {
    let inc: () -> Int
    let dec: () -> Int

    init(start: Int) {
        var n = start

        inc = { ++n }
        dec = { --n }
    }
}


let c = Counter(start: 10)

c.inc()  // 11
c.inc()  // 12
c.dec()  // 11

对于Swift 1-3:

不,不可能。这里根本没有任何私有/受保护的方法和变量。

一切都是公开的。

更新 从Swift 4开始,可能会在这个帖子中看到其他答案

语言语法没有关键字“public”,“private”或“protected”。这意味着一切都是公开的。当然,可以有一些替代方法来指定没有这些关键字的访问修饰符,但我在语言参考中找不到它。

现在在测试版4中,他们为Swift添加了访问修饰符。

from Xcode 6 beta 4 realese notes:

Swift access control has three access levels: private entities can only be accessed from within the source file where they are defined. internal entities can be accessed anywhere within the target where they are defined. public entities can be accessed from anywhere within the target and from any other context that imports the current target’s module. By default, most entities in a source file have internal access. This allows application developers to largely ignore access control while allowing framework developers full control over a framework's API.

从Xcode 6 beta 4开始,Swift就有了访问修饰符。发布说明如下:

Swift访问控制分为三种访问级别: 私有实体只能从定义它们的源文件中访问。 内部实体可以在目标中定义它们的任何地方访问。 公共实体可以从目标中的任何地方访问,也可以从导入当前目标模块的任何其他上下文访问。

隐式默认值是内部的,因此在应用程序目标中,您可以关闭访问修饰符,除非在需要更严格限制的地方。在框架目标中(例如,如果你嵌入一个框架来在应用程序和共享或Today视图扩展之间共享代码),使用public指定你想要向框架的客户端公开的API。