Swift 3.1 中自定义初始化程序的访问级别

Access levels of custom initializers in Swift 3.1

引自 Swift 编程语言 (Swift 3.1):

Custom initializers can be assigned an access level less than or equal to the type that they initialize. The only exception is for required initializers (as defined in Required Initializers). A required initializer must have the same access level as the class it belongs to.

如果是这样,为什么这段代码可以编译并工作?

private class GoofyClass {
    public init(mood: String) {}
    public required init(isCrazy: Bool) {}
}

private let shock = GoofyClass(mood: "shocked")
private let crazy = GoofyClass(isCrazy: true)

在 Swift 中,class 的成员或结构的访问级别比 class/struct 本身限制更少,会自动降级到与 class/struct 相同的级别.我相信这是语言设计者的一个深思熟虑的设计决定。

在你的例子中,假设 class 在文件的顶层声明(即它没有嵌套在另一个类型中),你声明的 inits public 实际上是 fileprivate

The only exception is for required initializers (as defined in Required Initializers). A required initializer must have the same access level as the class it belongs to.

这是指您不能使所需初始化程序的访问级别比其class更限制,例如

open class Foo 
{
    internal required init() // error
}