我有以下代码(请忽略拼写错误:))
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
仅对OwnsVehical
是VechicalType
的HeavyVehical
可用。
这就是为什么您不能在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
,从而可以调用所需的方法。