为什么ClassA采用ProtocolB不满足ProtocolB要求

时间:2017-11-22 17:14:44

标签: swift

我在下面创建了游乐场代码,以说明我对当前项目的困难。任何人都可以帮我理解最后一行的编译器错误吗?

import Foundation

//******************************************************************************
//                            This Compiles
//******************************************************************************

protocol Protocol1 : AnyObject {
    var related: [Protocol2] { get set }
}

protocol Protocol2 : AnyObject {
    var related: [Protocol1] { get set }
}

class Class1 : Protocol1 {
    var related = [Protocol2]()
}

class Class2 : Protocol2 {
    var related = [Protocol1]()
}

let class1 = Class1()
let class2 = Class2()
class2.related.append(class1)


//******************************************************************************
//                            This Does Not Compile
//******************************************************************************

class Weak<T: AnyObject> {
    weak var reference : T?
    init (_ reference: T) {
        self.reference = reference
    }
}

protocol ProtocolA : AnyObject {
    var related: [Weak<ProtocolB>] { get set }
}

protocol ProtocolB : AnyObject {
    var related: [Weak<ProtocolA>] { get set }
}

class ClassA : ProtocolA {
    var related = [Weak<ProtocolB>]()
}

class ClassB : ProtocolB {
    var related = [Weak<ProtocolA>]()
}

let classA = ClassA()
let classB = ClassB()
classA.related.append(Weak(classB)) // <= Cannot convert value of type 'Weak<ClassB>' to expected argument type 'Weak<ProtocolB>'

[我在这个问题的底部添加了单词,以便有足够的单词使堆栈溢出“正确性检查器”高兴。我确实认为没有什么可以说明我的问题更清晰了。编译器错误说明了一切]

0 个答案:

没有答案