首页 > 解决方案 > 为什么我不能将此协议符合类分配给协议类型的变量?

问题描述

我在这里有一个玩具示例,我在网上找不到任何解决方案。

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>())
}

任何指示或解释将不胜感激。

标签: swiftswift-protocols

解决方案


我不明白这种情况的背景。但是,我提供了两种解决方案:

1:

class Bar<F:Foo> {
    let foo: FooClass.F

    init(){
        foo = FooClass.F()
    }
}

2:

class Bar<F:Foo> {
    let foo: FooClass

    init(){
        foo = FooClass()
    }
}

无论你试图实现什么,你目前正在做的事情都没有逻辑意义


推荐阅读