swift - 为什么我不能将此协议符合类分配给协议类型的变量?
问题描述
我在这里有一个玩具示例,我在网上找不到任何解决方案。
protocol Tree {
associatedtype Element
// some nice tree functions
}
class BinaryTree<T> : Tree {
typealias Element = T
}
class RedBlackTree<T> : Tree {
typealias Element = T
}
enum TreeType {
case binaryTree
case redBlackTree
}
// Use a generic `F` because Tree has an associated type and it can no
// longer be referenced directly as a type. This is probably the source
// of the confusion.
class TreeManager<E, F:Tree> where F.Element == E {
let tree: F
init(use type: TreeType){
// Error, cannot assign value of type 'BinaryTree<E>' to type 'F'
switch(type){
case .binaryTree:
tree = BinaryTree<E>()
case .redBlackTree:
tree = RedBlackTree<E>()
}
}
}
我不确定这里的问题是什么,或者我应该寻找什么才能弄清楚。我仍在考虑协议,因为我将使用另一种语言进行接口,并且我将 aBinaryTree
视为 a 的有效实现,Tree
唯一的限制F
是它必须是 a Tree
。更令人困惑的是,我不确定为什么下面的代码片段可以编译,因为上面的代码片段没有。
func weird<F:Tree>(_ f: F){ }
func test(){
// No error, BinaryTree can be assigned to an F:Tree
weird(BinaryTree<String>())
}
任何指示或解释将不胜感激。
解决方案
我不明白这种情况的背景。但是,我提供了两种解决方案:
1:
class Bar<F:Foo> {
let foo: FooClass.F
init(){
foo = FooClass.F()
}
}
2:
class Bar<F:Foo> {
let foo: FooClass
init(){
foo = FooClass()
}
}
无论你试图实现什么,你目前正在做的事情都没有逻辑意义
推荐阅读
- javascript - 如何将列表列表转换为 Javascript 中的哈希映射/“字典”?
- javascript - 如何通过套接字传递 Postgres 池或客户端
- .htaccess - 使用 htaccess 将包含特定部分的所有页面重定向到主页
- python - Django/Graphene 似乎在测试运行中的各个测试之间清理数据库
- c++ - 如何在 VSCode 中使用 C++ 的 Boost?
- angular - 从 Spring 请求哈希数时,Angular 中的“JSON 语法错误:意外数字”
- firebase - 为 Firebase 启用 Cloud Storage 时出现未知错误
- graphql - 在苗条和动态路由中无需刷新的页面加载
- javascript - 用户的 JavaScript 表单
- java - hibernate 不会在注册日期之前搜索信息