Swift 泛型引用类型

标签 swift generics protocols weak

我在尝试将通用类型要求限制为仅引用类型时遇到问题。下面是一些示例代码:

class WeakHolder<Element: AnyObject> {
    weak var element: Element?

    init(element: Element) {
        self.element = element
    }
}

protocol Animal: class { }

class Dog: Animal { }

let dog: Animal = Dog()
let holder = WeakHolder<Animal>(element: dog) // Error: Using "Animal" as a concrete type conforming to protocol 'AnyObject' is not supported.

如果我将通用要求更改为 <Element: class> , 我收到错误 class constraint can only appear on protocol declarations .

这是泛型的限制吗?将协议(protocol)标记为类就足以对该协议(protocol)进行弱引用,泛型中没有等效项吗?

最佳答案

简单的答案是,您不能拥有作为协议(protocol)的通用类型。

写出语法可以清楚地说明它是如何工作的: class/struct GenericType<TypeName: TypeConstraints> {}

let thing = GenericType<Type>() where Type is a class or struct that adheres to any constraints

要求采用类型成为类的协议(protocol)意味着任何采用者都是类,但协议(protocol)本身仍然不是类型。

泛型有可能在某个时候支持协议(protocol),但这需要将通用方法更改为协议(protocol)或泛型。尽管您的具体示例可能会在幕后进行少量工作,但有可能在某个时候实现。

可以看看The Generics Manifesto如果你想看到他们前进的方向。略读了一下,我没有发现任何与您的用例直接相关的内容,但它非常具体,因此可能不会包含在文档的参数中。

关于Swift 泛型引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40897924/

相关文章:

swift - Objective-C 可选协议(protocol)方法的默认实现

c# - 串行数据的二进制通信协议(protocol)解析器设计

Python 高速公路 WAMP 消息传递协议(protocol)

ios - Popoverview 不以 iPad 旋转为中心

c# - 将 IList<T> 转换为 BindingList<T>

scala - value === 不是类型参数 TKey 的成员(使用 Squeryl)

c# - 如何编写指定创建逻辑的接口(interface)或抽象类?

ios - Swift 中的集合和协议(protocol)

arrays - 二维数组扩展 Swift 3.1.1

ios - swift - uilalertcontroller 文本字段值返回空