gpt4 book ai didi

Swift 在递归使用时假定泛型类型

转载 作者:行者123 更新时间:2023-11-28 11:30:50 24 4
gpt4 key购买 nike

足够简单的例子:

protocol Fulfilment {
}

class Node<T: Fulfilment> {
var object: T
var children: [Node]

init(object: T, children: [Node] = []) {
self.object = object
self.children = children
}
}

struct One: Fulfilment {
}

struct Two: Fulfilment {
}

let node1 = Node<One>(object: One())
let node2 = Node<Two>(object: Two(), children: [node1])

我在最后一行收到一个错误,因为 node1不是 Two 类型尽管我没有指定通用类型应该应用于 children .编译器对待代码就像我写的一样

var children: [Node<T>]

我想要符合相同泛型类型的假设让我很头疼。我能以某种方式告诉 Swift 我不想要这种行为吗?

最佳答案

问题是没有这样的类型 Node没有特定的通用类型参数和特殊版本的 Node ,例如 Node<One>Node<Two>是完全不相关的类型,所以你不能存储 Node 的数组与不同object无论如何类型。因此编译器推断 children类型为 Node<T> .

关于Swift 在递归使用时假定泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56757553/

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