gpt4 book ai didi

swift - Swift 3.1 中自定义初始化器的访问级别

转载 作者:行者123 更新时间:2023-11-28 12:20:23 25 4
gpt4 key购买 nike

引自 The Swift Programming Language (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 中,访问级别限制低于类/结构本身的类或结构的成员会自动降级到与类/结构相同的级别。我相信这是语言设计者经过深思熟虑的设计决定。

在你的例子中,假设类是在文件的顶层声明的(即它没有嵌套在另一个类型中),你声明的 initpublic 实际上是 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.

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

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

关于swift - Swift 3.1 中自定义初始化器的访问级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45046487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com