协议中的公共默认初始化 [英] Public default init in protocol

查看:69
本文介绍了协议中的公共默认初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

public protocol MyProtocol {
    init()
}

public extension MyProtocol {
    public init() {
        self.init()
    }
}

public final class MyClass: MyProtocol {}

我收到一条错误消息:

Initializer 'init()' 必须声明为 public,因为它匹配一个公共协议MyProtocol"中的要求

Initializer 'init()' must be declared public because it matches a requirement in public protocol 'MyProtocol'

如果我在 final 之前删除访问控制 (public),它会起作用.但为什么?有什么办法可以让协议处理 init 吗?我认为默认情况下协议的所有成员都是隐式public.

If I remove the access control (public) before final, it works. But why? Is there any way I can let the protocol handle the init? I thought all members of protocols are implicitly public by default.

更奇怪的是,一个不同的init只能在extension中找到,默认是public:

More strange is that a different init that can only be found in the extension is public by default:

public protocol MyProtocol {
    init()
}

public extension MyProtocol {
    public init() {
        self.init()
    }

    public init(youDoNotHaveToImplementMe: Any) {
        self.init()
    }
}

public final class MyClass: MyProtocol {
    public init() {}
}

如您所见,新的 init 实际上是 public.我希望我的普通 init 也应该是 public .为什么不是这样?

As you can see, the new init is actually public. I expected my normal init should be public as well. Why is this not the case?

推荐答案

MyClass 应该符合给定的协议 MyProtocol,即使 MyClass> 是公开的.但是,如果 MyClass 是公开的,但它的 init 从其他模块中看不到,那么 MyClass 如何符合 MyProtocol 呢?它将符合 MyProtocol(签名是这么说的),同时不符合(没有可见的 init).

MyClass is supposed to conform to given protocol MyProtocol, even if MyClass is public. But how would MyClass conform to MyProtocol, if MyClass were public but its init not visible from the other module? It would conform to MyProtocol(signature says so) and at the same time not(no visible init).

由于您的协议不能确定涵盖使用它的类的所有成员,因此您在协议中声明的任何初始化程序都需要将类的未知"成员的初始化委托给该类提供的另一个初始化程序自己.

Since your protocol can't be certain to cover all members of the class that uses it, any initializer you declare in your protocol will need to delegate initialization of the "unknown" members of the class to another initializer provided by the class itself.

来源

由于 MyClass 的默认初始化器是内部的,如果 MyClass 是公共的,而没有在类中声明 public init,则协议不符合协议.

Since MyClass‘ default initializer is internal the protocol does not conform to the protocol if no public init is declared in-class while MyClass is public.

这篇关于协议中的公共默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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