我有以下代码(请忽略拼写错误:))

protocol Vehical {
    var wheelsCount:Int {get}
}

protocol LightVehical:Vehical {
    func tankWithPetrol (liters:Int)
}

protocol HeavyVehical:Vehical {
    func tankWithDisel(liters:Int)
}

protocol OwnsVehical {
    associatedtype VechicalType = Vehical
    var vehical:VechicalType {get}
}

// Here I have == for constraint
extension OwnsVehical where VechicalType == HeavyVehical {
    func fillTankWithDisel() {

    }
}
 // Light Vehicle
struct VolVOV90 : LightVehical {

    var wheelsCount: Int = 4

    func tankWithPetrol(liters: Int) {

    }
}
     // Heavy Vehicle

struct Van : HeavyVehical {
    func tankWithDisel(liters: Int) {

    }

    var wheelsCount: Int = 6


}

struct PersonWithHeavyVehical:OwnsVehical {
    typealias VechicalType = Van
    let vehical = Van()
}


现在当我尝试

let personWithHeavyV = PersonWithHeavyVehical()
personWithHeavyV.fillTankWithDisel() // It is not compiling with ==


如果我改变

extension OwnsVehical where VechicalType == HeavyVehical




extension OwnsVehical where VechicalType : HeavyVehical


代码编译成功,我没有找到==与之间的区别And:任何人都可以帮助我理解它,谢谢

最佳答案

当您这样做时:

extension OwnsVehical where VechicalType == HeavyVehical

您告诉编译器VechicalType必须是HeavyVehical类型。这意味着方法fillTankWithDisel仅对OwnsVehicalVechicalTypeHeavyVehical可用。
这就是为什么您不能在fillTankWithDisel上调用personWithHeavyV的原因,因为personWithHeavyV不是HeavyVehical,而是Van

当您这样做时:

extension OwnsVehical where VechicalType : HeavyVehical

您告诉编译器VechicalType符合HeavyVehical协议,因此您可以调用personWithHeavyV.fillTankWithDisel,因为personWithHeavyV符合OwnsVehical且没有其他限制,可以调用。

如果要fillTankWithDisel进行编译,则必须将结构PersonWithHeavyVehical的实现更改为以下内容:

personWithHeavyV.fillTankWithDisel()

现在,您有了一个VccicalType为struct PersonWithHeavyVehical: OwnsVehical { typealias VechicalType = HeavyVehical let vehical = Van()}personWithHeavyV,从而可以调用所需的方法。

10-08 12:18