swift - 如何在 Swift 中将继承应用于泛型

标签 swift generics inheritance

我有一个通用容器结构,它存储为实现如下协议(protocol)的类的容器:

protocol Protocol {}
class Class : Protocol {}
struct Container<Element> {
    var value:Element
    init(_ v:Element) { value = v }
}
class Example {
    var container : Container<Class>
    init() { container = Container(Class()) }
    func getContainer() -> Container<Protocol> { return container }
}

但是,当我传递它时,我想将它作为协议(protocol)的容器传递,该协议(protocol)在返回容器上生成错误:

Cannot convert return expression of type 'Container<Class>' to return type 'Container<Protocol>'

我知道这应该是可能的,因为 Swift 使用数组来做到这一点,如下所示:

class ArrayExample {
    var arrayContainer : [Class]
    init() { arrayContainer = [Class()] }
    func getArrayContainer() -> [Protocol] { return arrayContainer }
}

那么有没有人对如何实现容器有任何想法,以便转换/复制不会产生错误

最佳答案

尚不清楚您实际想要实现的目标,但这里是可编译的代码,涵盖了您迄今为止表达的所有目标:

protocol Protocol {}
class Class : Protocol {
    var thing : AnyObject?
}
class Container<Element> {
    var value:Element
    init(_ v:Element) { value = v }
}
class Example {
    var container : Container<Protocol>
    init() { container = Container(Class()) }
    func getContainer() -> Container<Protocol> { return container }
    func doStuff() {
        if let v = container.value as? Class { v.thing = "ha" }
    }
}

关于swift - 如何在 Swift 中将继承应用于泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32998030/

相关文章:

ios - 如何从另一个 View Controller 加载webview?

ios - 上传到 firebase 的视频长度为 0 秒?

asp.net-mvc - ASP.NET MVC - 为什么我的 View 不能从 System.Web.Mvc.ViewPage(of T) 正确继承

java - 调用从基类 : use this , super 继承的方法或隐式调用的最佳方法

css - 如果我们不指定这些元素的参数和值,某些元素是否会继承其同级元素的参数值?

SwiftUI 无法返回函数 View

ios - 无法向我的闹钟应用程序发送通知

c# - 为什么这个泛型方法调用的是基类方法,而不是派生类方法呢?

java - 只允许 ArrayList 中的特定类型

c++ - 多重继承和unique_ptr销毁