具有类绑定约束的泛型类不能通过类绑定协议进行参数化 [英] Generic class with class-bound constraint cannot be parametrized by class-bound protocol

查看:30
本文介绍了具有类绑定约束的泛型类不能通过类绑定协议进行参数化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一个对象有一个通用的弱引用,并通过一个类绑定的协议对其进行参数化.

I'd like to have a generic weak reference to an object and parametrize it by a protocol that is class-bound.

这是在我的情况下不起作用的代码示例:

Here is the code example that does not work in my case:

protocol Protocol: class { // also written as `protocol Protocol: AnyObject {`
    func function()
}


final class A: Protocol {
    func function() {}
}

final class Weak<Type> where Type: AnyObject {
    final private weak var property: Type?

    init(property: Type) {
        self.property = property
    }
}

let a = A()
let something = Weak<Protocol>(property: a) // error: 'Weak' requires that 'Protocol' be a class type

我在最后一行遇到错误:'Weak'要求'Protocol'是类类型.

I get an error on last line: 'Weak' requires that 'Protocol' be a class type.

由于 Protocol 将始终为 class 类型(与 AnyObject 相同),编译器不应该允许吗?是否有可能通过Swift 4解决该问题?

As Protocol will always be of class type (which is the same as AnyObject) shouldn't that be allowed by the compiler? Is it possible to resolve that issue with swift 4?

如果不是,这是可以在swift的未来版本中解决的限制,还是类型系统不允许发生的事情?

If not, is it a limitation that can be resolved in a future version of swift or is it something impossible that the type system can not allow to happen?

一个不被接受的解决方案是使用 @objc 进行协议声明,如下所示:

A not accepted solution is to use @objc to the protocol declaration as in:

@obc protocol Protocol: class {
    func function()
}

因为这会带来局限性.

推荐答案

您是在说:

final class Weak<Type> where Type: AnyObject {

所以您自己需要将Type设为一个类(因为这正是AnyObject的意思).

So you yourself are requiring that Type be a class (because that is exactly what AnyObject means).

协议不是 类.这是一个协议.

A protocol is not a class. It is a protocol.

这篇关于具有类绑定约束的泛型类不能通过类绑定协议进行参数化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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